Salome HOME
Implementation of producer/consumer mechanism and transaction mechanism for global...
[modules/yacs.git] / src / SALOMESDS / SALOMESDS_PickelizedPyObjServer.cxx
1 // Copyright (C) 2007-2015  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19 // Author : Anthony GEAY (EDF R&D)
20
21 #include "SALOMESDS_PickelizedPyObjServer.hxx"
22 #include "SALOMESDS_DataScopeServer.hxx"
23 #include "SALOMESDS_Exception.hxx"
24
25 #include <iostream>
26 #include <sstream>
27
28 using namespace SALOMESDS;
29
30 PickelizedPyObjServer::PickelizedPyObjServer(DataScopeServerBase *father, const std::string& varName, const SALOME::ByteVec& value):BasicDataServer(father,varName),_self(0)
31 {
32   setSerializedContentInternal(value);
33 }
34
35 //! obj is consumed
36 PickelizedPyObjServer::PickelizedPyObjServer(DataScopeServerBase *father, const std::string& varName, PyObject *obj):BasicDataServer(father,varName),_self(0)
37 {
38   setNewPyObj(obj);
39 }
40
41 PickelizedPyObjServer::~PickelizedPyObjServer()
42 {
43   Py_XDECREF(_self);
44 }
45
46 /*!
47  * Called remotely -> to protect against throw
48  */
49 SALOME::ByteVec *PickelizedPyObjServer::fetchSerializedContent()
50 {
51   Py_XINCREF(_self);//because pickelize consume _self
52   return FromCppToByteSeq(pickelize(_self));
53 }
54
55 bool PickelizedPyObjServer::isDict()
56 {
57   if(PyDict_Check(_self))
58     return true;
59   else
60     return false;
61 }
62
63 void PickelizedPyObjServer::checkKeyNotAlreadyPresent(PyObject *key)
64 {
65   checkKeyPresence(key,false);
66 }
67
68 void PickelizedPyObjServer::checkKeyPresent(PyObject *key)
69 {
70   checkKeyPresence(key,true);
71 }
72
73 void PickelizedPyObjServer::addKeyValueHard(PyObject *key, PyObject *value)
74 {
75   bool isOK(PyDict_SetItem(_self,key,value)==0);
76   if(!isOK)
77     throw Exception("PickelizedPyObjServer::addKeyValueHard : error when trying to add key,value to dict !");
78 }
79
80 void PickelizedPyObjServer::addKeyValueErrorIfAlreadyExisting(PyObject *key, PyObject *value)
81 {
82   checkKeyNotAlreadyPresent(key);
83   bool isOK(PyDict_SetItem(_self,key,value)==0);
84   if(!isOK)
85     throw Exception("PickelizedPyObjServer::addKeyValueErrorIfAlreadyExisting : error when trying to add key,value to dict !");
86 }
87
88 void PickelizedPyObjServer::removeKeyInVarErrorIfNotAlreadyExisting(PyObject *key)
89 {
90   checkKeyPresent(key);
91   if(PyDict_DelItem(_self,key)!=0)
92     throw Exception("PickelizedPyObjServer::removeKeyInVarErrorIfNotAlreadyExisting : error during deletion of key in dict !");
93 }
94
95 void PickelizedPyObjServer::FromByteSeqToCpp(const SALOME::ByteVec& bsToBeConv, std::string& ret)
96 {
97   std::size_t sz(bsToBeConv.length());
98   ret.resize(sz,' ');
99   char *buf(const_cast<char *>(ret.c_str()));
100   for(std::size_t i=0;i<sz;i++)
101     buf[i]=bsToBeConv[i];
102 }
103
104 SALOME::ByteVec *PickelizedPyObjServer::FromCppToByteSeq(const std::string& strToBeConv)
105 {
106   SALOME::ByteVec *ret(new SALOME::ByteVec);
107   const char *buf(strToBeConv.c_str());
108   std::size_t sz(strToBeConv.size());
109   ret->length(sz);
110   for(std::size_t i=0;i<sz;i++)
111     (*ret)[i]=buf[i];
112   return ret;
113 }
114
115 //! New reference returned
116 PyObject *PickelizedPyObjServer::GetPyObjFromPickled(const std::string& pickledData, DataScopeServerBase *dsb)
117 {
118   std::size_t sz(pickledData.size());
119   PyObject *pickledDataPy(PyString_FromStringAndSize(NULL,sz));// agy : do not use PyString_FromString because std::string hides a vector of byte.
120   char *buf(PyString_AsString(pickledDataPy));// this buf can be used thanks to python documentation.
121   const char *inBuf(pickledData.c_str());
122   std::copy(inBuf,inBuf+sz,buf);
123   PyObject *selfMeth(PyObject_GetAttrString(dsb->getPickler(),"loads"));
124   PyObject *args(PyTuple_New(1)); PyTuple_SetItem(args,0,pickledDataPy);
125   PyObject *ret(PyObject_CallObject(selfMeth,args));
126   Py_XDECREF(args);
127   Py_XDECREF(selfMeth);
128   return ret;
129 }
130
131 //! New reference returned
132 PyObject *PickelizedPyObjServer::getPyObjFromPickled(const std::string& pickledData)
133 {
134   return GetPyObjFromPickled(pickledData,_father);
135 }
136
137 //! New reference returned
138 PyObject *PickelizedPyObjServer::GetPyObjFromPickled(const std::vector<unsigned char>& pickledData, DataScopeServerBase *dsb)
139 {
140   std::size_t sz(pickledData.size());
141   PyObject *pickledDataPy(PyString_FromStringAndSize(NULL,sz));// agy : do not use PyString_FromString because std::string hides a vector of byte.
142   char *buf(PyString_AsString(pickledDataPy));// this buf can be used thanks to python documentation.
143   const unsigned char *inBuf(&pickledData[0]);
144   std::copy(inBuf,inBuf+sz,buf);
145   PyObject *selfMeth(PyObject_GetAttrString(dsb->getPickler(),"loads"));
146   PyObject *args(PyTuple_New(1)); PyTuple_SetItem(args,0,pickledDataPy);
147   PyObject *ret(PyObject_CallObject(selfMeth,args));
148   Py_XDECREF(args);
149   Py_XDECREF(selfMeth);
150   return ret;
151 }
152
153 //! New reference returned
154 PyObject *PickelizedPyObjServer::getPyObjFromPickled(const std::vector<unsigned char>& pickledData)
155 {
156   return GetPyObjFromPickled(pickledData,_father);
157 }
158
159 //! obj is consumed by this method.
160 std::string PickelizedPyObjServer::Pickelize(PyObject *obj, DataScopeServerBase *dsb)
161 {
162   PyObject *args(PyTuple_New(2));
163   PyTuple_SetItem(args,0,obj);
164   PyTuple_SetItem(args,1,PyInt_FromLong(2));// because "assert(cPickle.HIGHEST_PROTOCOL is 2)"
165   PyObject *selfMeth(PyObject_GetAttrString(dsb->getPickler(),"dumps"));
166   PyObject *retPy(PyObject_CallObject(selfMeth,args));
167   Py_XDECREF(selfMeth);
168   Py_XDECREF(args);
169   std::size_t sz(PyString_Size(retPy));
170   std::string ret(sz,'\0');
171   const char *buf(PyString_AsString(retPy));
172   char *inBuf(const_cast<char *>(ret.c_str()));
173   for(std::size_t i=0;i<sz;i++)
174     inBuf[i]=buf[i];
175   Py_XDECREF(retPy);
176   return ret;
177 }
178
179 //! obj is consumed by this method.
180 std::string PickelizedPyObjServer::pickelize(PyObject *obj)
181 {
182   return Pickelize(obj,_father);
183 }
184
185 //! obj is consumed by this method.
186 void PickelizedPyObjServer::setNewPyObj(PyObject *obj)
187 {
188   if(!obj)
189     throw Exception("PickelizedPyObjServer::setNewPyObj : trying to assign a NULL pyobject in this !");
190   if(obj==_self)
191     return ;
192   if(PyList_Check(obj)==0 && PyDict_Check(obj)==0 && PyTuple_Check(obj)==0 && PyString_Check(obj)==0 && PyInt_Check(obj)==0 && PyBool_Check(obj)==0 && PyFloat_Check(obj)==0 && obj!=Py_None)
193     throw Exception("PickelizedPyObjServer::setNewPyObj : Supported python types are [list,tuple,dict,str,int,bool,float,None] !");
194   if(_self)
195     {
196       PyObject *selfType(PyObject_Type(_self));
197       if(PyObject_IsInstance(obj,selfType)!=1)
198         {
199           Py_XDECREF(obj);
200           Py_XDECREF(selfType);
201           throw Exception("PickelizedPyObjServer::setNewPyObj : type of new object is not the same than those previously set !");
202         }
203       else
204         Py_XDECREF(selfType);
205     }
206   Py_XDECREF(_self);
207   _self=obj;
208 }
209
210 void PickelizedPyObjServer::setSerializedContentInternal(const SALOME::ByteVec& newValue)
211 {
212   std::string data;
213   FromByteSeqToCpp(newValue,data);
214   setNewPyObj(getPyObjFromPickled(data));
215 }
216
217 PyObject *PickelizedPyObjServer::CreateDftObjFromType(PyObject *globals, const std::string& typeName)
218 {
219   PyObject *builtins(PyDict_GetItemString(globals,"__builtins__"));
220   if(!builtins)
221     throw Exception("PickelizedPyObjServer constructor : no __builtins__ in globals !");
222   PyObject *builtins2(PyModule_GetDict(builtins));
223   if(!builtins2)
224     throw Exception("PickelizedPyObjServer constructor : internal error fail to invoke __dict__ on __builtins__ !");
225   PyObject *tmp(PyDict_GetItemString(builtins2,typeName.c_str()));
226   if(!tmp)
227     {
228       std::ostringstream oss; oss << "PickelizedPyObjServer::CreateDftObjFromType : Invalid type name \"" << typeName << "\" !";
229       throw Exception(oss.str());
230     }
231   PyObject *args(PyTuple_New(0));
232   PyObject *ret(PyObject_CallObject(tmp,args));
233   Py_XDECREF(args);
234   return ret;
235 }
236
237 void PickelizedPyObjServer::checkKeyPresence(PyObject *key, bool presence)
238 {
239   if(!isDict())
240     throw Exception("PickelizedPyObjServer::checkKeyPresence : not a dict !");
241   PyObject *selfMeth(PyObject_GetAttrString(_self,"__contains__"));//new ref
242   PyObject *args(PyTuple_New(1));
243   PyTuple_SetItem(args,0,key); Py_XINCREF(key);// key is stolen by PyTuple_SetItem
244   PyObject *retPy(PyObject_CallObject(selfMeth,args));
245   Py_XDECREF(args);
246   Py_XDECREF(selfMeth);
247   //
248   if(retPy!=Py_False && retPy!=Py_True)
249     throw Exception("PickelizedPyObjServer::checkKeyPresence : unexpected return of dict.__contains__ !");
250   if(!presence)
251     {
252       if(retPy==Py_True)
253         throw Exception("PickelizedPyObjServer::checkKeyPresence : key is already present and it should not !");
254     }
255   else
256     {
257       if(retPy==Py_False)
258         throw Exception("PickelizedPyObjServer::checkKeyPresence : key is not present and it should !");
259     }
260   Py_XDECREF(retPy);
261 }