p3dPythonRun.cxx 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502
  1. // Filename: p3dPythonRun.cxx
  2. // Created by: drose (05Jun09)
  3. //
  4. ////////////////////////////////////////////////////////////////////
  5. //
  6. // PANDA 3D SOFTWARE
  7. // Copyright (c) Carnegie Mellon University. All rights reserved.
  8. //
  9. // All use of this software is subject to the terms of the revised BSD
  10. // license. You should have received a copy of this license along
  11. // with this source code in a file named "LICENSE."
  12. //
  13. ////////////////////////////////////////////////////////////////////
  14. #include "p3dPythonRun.h"
  15. #include "asyncTaskManager.h"
  16. #include "binaryXml.h"
  17. // There is only one P3DPythonRun object in any given process space.
  18. // Makes the statics easier to deal with, and we don't need multiple
  19. // instances of this thing.
  20. P3DPythonRun *P3DPythonRun::_global_ptr = NULL;
  21. ////////////////////////////////////////////////////////////////////
  22. // Function: P3DPythonRun::Constructor
  23. // Access: Public
  24. // Description:
  25. ////////////////////////////////////////////////////////////////////
  26. P3DPythonRun::
  27. P3DPythonRun(int argc, char *argv[]) {
  28. _read_thread_continue = false;
  29. _program_continue = true;
  30. INIT_LOCK(_commands_lock);
  31. INIT_THREAD(_read_thread);
  32. _session_id = 0;
  33. _next_sent_id = 0;
  34. _program_name = argv[0];
  35. _py_argc = 1;
  36. _py_argv = (char **)malloc(2 * sizeof(char *));
  37. _py_argv[0] = argv[0];
  38. _py_argv[1] = NULL;
  39. #ifdef NDEBUG
  40. // In OPTIMIZE 4 compilation mode, run Python in optimized mode too.
  41. extern int Py_OptimizeFlag;
  42. Py_OptimizeFlag = 2;
  43. #endif
  44. // Turn off the automatic load of site.py at startup.
  45. extern int Py_NoSiteFlag;
  46. Py_NoSiteFlag = 1;
  47. // Initialize Python. It appears to be important to do this before
  48. // we open the pipe streams and spawn the thread, below.
  49. Py_SetProgramName((char *)_program_name.c_str());
  50. Py_Initialize();
  51. PySys_SetArgv(_py_argc, _py_argv);
  52. // Open the pipe streams with the input and output handles from the
  53. // parent.
  54. #ifdef _WIN32
  55. HANDLE read = GetStdHandle(STD_INPUT_HANDLE);
  56. HANDLE write = GetStdHandle(STD_OUTPUT_HANDLE);
  57. if (!SetStdHandle(STD_INPUT_HANDLE, INVALID_HANDLE_VALUE)) {
  58. nout << "unable to reset input handle\n";
  59. }
  60. if (!SetStdHandle(STD_OUTPUT_HANDLE, INVALID_HANDLE_VALUE)) {
  61. nout << "unable to reset input handle\n";
  62. }
  63. _pipe_read.open_read(read);
  64. _pipe_write.open_write(write);
  65. #else
  66. _pipe_read.open_read(STDIN_FILENO);
  67. _pipe_write.open_write(STDOUT_FILENO);
  68. #endif // _WIN32
  69. if (!_pipe_read) {
  70. nout << "unable to open read pipe\n";
  71. }
  72. if (!_pipe_write) {
  73. nout << "unable to open write pipe\n";
  74. }
  75. spawn_read_thread();
  76. }
  77. ////////////////////////////////////////////////////////////////////
  78. // Function: P3DPythonRun::Destructor
  79. // Access: Public
  80. // Description:
  81. ////////////////////////////////////////////////////////////////////
  82. P3DPythonRun::
  83. ~P3DPythonRun() {
  84. Py_Finalize();
  85. join_read_thread();
  86. DESTROY_LOCK(_commands_lock);
  87. }
  88. ////////////////////////////////////////////////////////////////////
  89. // Function: P3DPythonRun::run_python
  90. // Access: Public
  91. // Description: Runs the embedded Python process. This method does
  92. // not return until the plugin is ready to exit.
  93. ////////////////////////////////////////////////////////////////////
  94. bool P3DPythonRun::
  95. run_python() {
  96. #if defined(_WIN32) && defined(USE_DEBUG_PYTHON)
  97. // On Windows, in a debug build, we have to preload sys.dll_suffix =
  98. // "_d", so that the Panda DLL preloader can import the correct
  99. // filenames.
  100. PyRun_SimpleString("import sys; sys.dll_suffix = '_d'");
  101. #endif
  102. // First, load runp3d_frozen.pyd. Since this is a magic frozen pyd,
  103. // importing it automatically makes all of its frozen contents
  104. // available to import as well.
  105. PyObject *runp3d_frozen = PyImport_ImportModule("runp3d_frozen");
  106. if (runp3d_frozen == NULL) {
  107. PyErr_Print();
  108. return false;
  109. }
  110. Py_DECREF(runp3d_frozen);
  111. // So now we can import the module itself.
  112. PyObject *app_runner_module = PyImport_ImportModule("direct.p3d.AppRunner");
  113. if (app_runner_module == NULL) {
  114. PyErr_Print();
  115. return false;
  116. }
  117. // Get the pointers to the objects needed within the module.
  118. PyObject *app_runner_class = PyObject_GetAttrString(app_runner_module, "AppRunner");
  119. if (app_runner_class == NULL) {
  120. PyErr_Print();
  121. return false;
  122. }
  123. // Construct an instance of AppRunner.
  124. _runner = PyObject_CallFunction(app_runner_class, (char *)"");
  125. if (_runner == NULL) {
  126. PyErr_Print();
  127. return false;
  128. }
  129. Py_DECREF(app_runner_class);
  130. // Get the UndefinedObject class.
  131. _undefined_object_class = PyObject_GetAttrString(app_runner_module, "UndefinedObject");
  132. if (_undefined_object_class == NULL) {
  133. PyErr_Print();
  134. return false;
  135. }
  136. // And the "Undefined" instance.
  137. _undefined = PyObject_GetAttrString(app_runner_module, "Undefined");
  138. if (_undefined == NULL) {
  139. PyErr_Print();
  140. return false;
  141. }
  142. // Get the ConcreteStruct class.
  143. _concrete_struct_class = PyObject_GetAttrString(app_runner_module, "ConcreteStruct");
  144. if (_concrete_struct_class == NULL) {
  145. PyErr_Print();
  146. return false;
  147. }
  148. // Get the BrowserObject class.
  149. _browser_object_class = PyObject_GetAttrString(app_runner_module, "BrowserObject");
  150. if (_browser_object_class == NULL) {
  151. PyErr_Print();
  152. return false;
  153. }
  154. // Get the global TaskManager.
  155. _taskMgr = PyObject_GetAttrString(app_runner_module, "taskMgr");
  156. if (_taskMgr == NULL) {
  157. PyErr_Print();
  158. return false;
  159. }
  160. Py_DECREF(app_runner_module);
  161. // Construct a Python wrapper around our methods we need to expose to Python.
  162. static PyMethodDef p3dpython_methods[] = {
  163. { "check_comm", P3DPythonRun::st_check_comm, METH_VARARGS,
  164. "Poll for communications from the parent process" },
  165. { "request_func", P3DPythonRun::st_request_func, METH_VARARGS,
  166. "Send an asynchronous request to the plugin host" },
  167. { NULL, NULL, 0, NULL } /* Sentinel */
  168. };
  169. PyObject *p3dpython = Py_InitModule("p3dpython", p3dpython_methods);
  170. if (p3dpython == NULL) {
  171. PyErr_Print();
  172. return false;
  173. }
  174. PyObject *request_func = PyObject_GetAttrString(p3dpython, "request_func");
  175. if (request_func == NULL) {
  176. PyErr_Print();
  177. return false;
  178. }
  179. // Now pass that func pointer back to our AppRunner instance, so it
  180. // can call up to us.
  181. PyObject *result = PyObject_CallMethod(_runner, (char *)"setRequestFunc", (char *)"O", request_func);
  182. if (result == NULL) {
  183. PyErr_Print();
  184. return false;
  185. }
  186. Py_DECREF(result);
  187. Py_DECREF(request_func);
  188. // Now add check_comm() as a task. It can be a threaded task, but
  189. // this does mean that application programmers will have to be alert
  190. // to asynchronous calls coming in from JavaScript. We'll put it on
  191. // its own task chain so the application programmer can decide how
  192. // it should be.
  193. AsyncTaskManager *task_mgr = AsyncTaskManager::get_global_ptr();
  194. PT(AsyncTaskChain) chain = task_mgr->make_task_chain("JavaScript");
  195. // The default is not threaded (num_threads == 0), but if the app
  196. // programmer decides to enable threads, the default is TP_low
  197. // priority.
  198. chain->set_thread_priority(TP_low);
  199. PyObject *check_comm = PyObject_GetAttrString(p3dpython, "check_comm");
  200. if (check_comm == NULL) {
  201. PyErr_Print();
  202. return false;
  203. }
  204. // We have to make it a PythonTask, not just a GenericAsyncTask,
  205. // because we need the code in PythonTask that supports calling into
  206. // Python from a separate thread.
  207. _check_comm_task = new PythonTask(check_comm, "check_comm");
  208. _check_comm_task->set_task_chain("JavaScript");
  209. task_mgr->add(_check_comm_task);
  210. Py_DECREF(check_comm);
  211. // Finally, get lost in taskMgr.run().
  212. PyObject *done = PyObject_CallMethod(_taskMgr, (char *)"run", (char *)"");
  213. if (done == NULL) {
  214. PyErr_Print();
  215. return false;
  216. }
  217. Py_DECREF(done);
  218. return true;
  219. }
  220. ////////////////////////////////////////////////////////////////////
  221. // Function: P3DPythonRun::handle_command
  222. // Access: Private
  223. // Description: Handles a command received from the plugin host, via
  224. // an XML syntax on the wire. Ownership of the XML
  225. // document object is passed into this method.
  226. //
  227. // It's important *not* to be holding _commands_lock
  228. // when calling this method.
  229. ////////////////////////////////////////////////////////////////////
  230. void P3DPythonRun::
  231. handle_command(TiXmlDocument *doc) {
  232. TiXmlElement *xcommand = doc->FirstChildElement("command");
  233. if (xcommand != NULL) {
  234. bool needs_response = false;
  235. int want_response_id;
  236. if (xcommand->QueryIntAttribute("want_response_id", &want_response_id) == TIXML_SUCCESS) {
  237. // This command will be waiting for a response.
  238. needs_response = true;
  239. }
  240. const char *cmd = xcommand->Attribute("cmd");
  241. if (cmd != NULL) {
  242. if (strcmp(cmd, "init") == 0) {
  243. assert(!needs_response);
  244. // The only purpose of the "init" command is to send us a
  245. // unique session ID, which in fact we don't do much with.
  246. xcommand->Attribute("session_id", &_session_id);
  247. // We do use it to initiate our object id sequence with a
  248. // number at least a little bit distinct from other sessions,
  249. // though. No technical requirement that we do this, but it
  250. // does make debugging the logs a bit easier.
  251. _next_sent_id = _session_id * 1000;
  252. PyObject *obj = PyObject_CallMethod(_runner, (char*)"setSessionId", (char *)"i", _session_id);
  253. Py_XDECREF(obj);
  254. } else if (strcmp(cmd, "start_instance") == 0) {
  255. assert(!needs_response);
  256. TiXmlElement *xinstance = xcommand->FirstChildElement("instance");
  257. if (xinstance != (TiXmlElement *)NULL) {
  258. P3DCInstance *inst = new P3DCInstance(xinstance);
  259. start_instance(inst, xinstance);
  260. }
  261. } else if (strcmp(cmd, "terminate_instance") == 0) {
  262. assert(!needs_response);
  263. int instance_id;
  264. if (xcommand->QueryIntAttribute("instance_id", &instance_id) == TIXML_SUCCESS) {
  265. terminate_instance(instance_id);
  266. }
  267. } else if (strcmp(cmd, "setup_window") == 0) {
  268. assert(!needs_response);
  269. int instance_id;
  270. TiXmlElement *xwparams = xcommand->FirstChildElement("wparams");
  271. if (xwparams != (TiXmlElement *)NULL &&
  272. xcommand->QueryIntAttribute("instance_id", &instance_id) == TIXML_SUCCESS) {
  273. setup_window(instance_id, xwparams);
  274. }
  275. } else if (strcmp(cmd, "exit") == 0) {
  276. assert(!needs_response);
  277. terminate_session();
  278. } else if (strcmp(cmd, "pyobj") == 0) {
  279. // Manipulate or query a python object.
  280. handle_pyobj_command(xcommand, needs_response, want_response_id);
  281. } else if (strcmp(cmd, "script_response") == 0) {
  282. // Response from a script request. In this case, we just
  283. // store it away instead of processing it immediately.
  284. MutexHolder holder(_responses_lock);
  285. _responses.push_back(doc);
  286. // And now we must return out, instead of deleting the
  287. // document at the bottom of this method.
  288. return;
  289. } else if (strcmp(cmd, "drop_pyobj") == 0) {
  290. int object_id;
  291. if (xcommand->QueryIntAttribute("object_id", &object_id) == TIXML_SUCCESS) {
  292. SentObjects::iterator si = _sent_objects.find(object_id);
  293. if (si != _sent_objects.end()) {
  294. PyObject *obj = (*si).second;
  295. Py_DECREF(obj);
  296. _sent_objects.erase(si);
  297. }
  298. }
  299. } else {
  300. nout << "Unhandled command " << cmd << "\n";
  301. if (needs_response) {
  302. // Better send a response.
  303. TiXmlDocument doc;
  304. TiXmlElement *xresponse = new TiXmlElement("response");
  305. xresponse->SetAttribute("response_id", want_response_id);
  306. doc.LinkEndChild(xresponse);
  307. write_xml(_pipe_write, &doc, nout);
  308. }
  309. }
  310. }
  311. }
  312. delete doc;
  313. }
  314. ////////////////////////////////////////////////////////////////////
  315. // Function: P3DPythonRun::handle_pyobj_command
  316. // Access: Private
  317. // Description: Handles the pyobj command, which queries or modifies
  318. // a Python object from the browser scripts.
  319. ////////////////////////////////////////////////////////////////////
  320. void P3DPythonRun::
  321. handle_pyobj_command(TiXmlElement *xcommand, bool needs_response,
  322. int want_response_id) {
  323. TiXmlDocument doc;
  324. TiXmlElement *xresponse = new TiXmlElement("response");
  325. xresponse->SetAttribute("response_id", want_response_id);
  326. doc.LinkEndChild(xresponse);
  327. const char *op = xcommand->Attribute("op");
  328. if (op != NULL && !PyErr_Occurred()) {
  329. if (strcmp(op, "get_panda_script_object") == 0) {
  330. // Get Panda's toplevel Python object.
  331. PyObject *obj = PyObject_CallMethod(_runner, (char*)"getPandaScriptObject", (char *)"");
  332. if (obj != NULL) {
  333. xresponse->LinkEndChild(pyobj_to_xml(obj));
  334. Py_DECREF(obj);
  335. }
  336. } else if (strcmp(op, "set_browser_script_object") == 0) {
  337. // Set the Browser's toplevel window object.
  338. PyObject *obj;
  339. TiXmlElement *xvalue = xcommand->FirstChildElement("value");
  340. if (xvalue != NULL) {
  341. obj = xml_to_pyobj(xvalue);
  342. } else {
  343. obj = Py_None;
  344. Py_INCREF(obj);
  345. }
  346. PyObject *result = PyObject_CallMethod
  347. (_runner, (char *)"setBrowserScriptObject", (char *)"O", obj);
  348. Py_DECREF(obj);
  349. Py_XDECREF(result);
  350. } else if (strcmp(op, "call") == 0) {
  351. // Call the named method on the indicated object, or the object
  352. // itself if method_name isn't given.
  353. TiXmlElement *xobject = xcommand->FirstChildElement("object");
  354. if (xobject != NULL) {
  355. PyObject *obj = xml_to_pyobj(xobject);
  356. const char *method_name = xcommand->Attribute("method_name");
  357. // Build up a list of params.
  358. PyObject *list = PyList_New(0);
  359. TiXmlElement *xchild = xcommand->FirstChildElement("value");
  360. while (xchild != NULL) {
  361. PyObject *child = xml_to_pyobj(xchild);
  362. PyList_Append(list, child);
  363. Py_DECREF(child);
  364. xchild = xchild->NextSiblingElement("value");
  365. }
  366. // Convert the list to a tuple for the call.
  367. PyObject *params = PyList_AsTuple(list);
  368. Py_DECREF(list);
  369. // Now call the method.
  370. PyObject *result = NULL;
  371. if (method_name == NULL) {
  372. // No method name; call the object directly.
  373. result = PyObject_CallObject(obj, params);
  374. // Several special-case "method" names.
  375. } else if (strcmp(method_name, "__bool__") == 0) {
  376. result = PyBool_FromLong(PyObject_IsTrue(obj));
  377. } else if (strcmp(method_name, "__int__") == 0) {
  378. result = PyNumber_Int(obj);
  379. } else if (strcmp(method_name, "__float__") == 0) {
  380. result = PyNumber_Float(obj);
  381. } else if (strcmp(method_name, "__repr__") == 0) {
  382. result = PyObject_Repr(obj);
  383. } else if (strcmp(method_name, "__str__") == 0 ||
  384. strcmp(method_name, "toString") == 0) {
  385. result = PyObject_Str(obj);
  386. } else if (strcmp(method_name, "__set_property__") == 0) {
  387. // We call these methods __set_property__ et al instead of
  388. // __setattr__ et al, because they do not precisely
  389. // duplicate the Python semantics.
  390. char *property_name;
  391. PyObject *value;
  392. if (PyArg_ParseTuple(params, "sO", &property_name, &value)) {
  393. bool success = false;
  394. // If it already exists as an attribute, update it there.
  395. if (PyObject_HasAttrString(obj, property_name)) {
  396. if (PyObject_SetAttrString(obj, property_name, value) != -1) {
  397. success = true;
  398. } else {
  399. PyErr_Clear();
  400. }
  401. }
  402. // If the object supports the mapping protocol, store it
  403. // in the object's dictionary.
  404. if (!success && PyMapping_Check(obj)) {
  405. if (PyMapping_SetItemString(obj, property_name, value) != -1) {
  406. success = true;
  407. } else {
  408. PyErr_Clear();
  409. }
  410. }
  411. // Finally, try to store it on the object.
  412. if (!success) {
  413. if (PyObject_SetAttrString(obj, property_name, value) != -1) {
  414. success = true;
  415. } else {
  416. PyErr_Clear();
  417. }
  418. }
  419. if (success) {
  420. result = Py_True;
  421. } else {
  422. result = Py_False;
  423. }
  424. Py_INCREF(result);
  425. }
  426. } else if (strcmp(method_name, "__del_property__") == 0) {
  427. char *property_name;
  428. if (PyArg_ParseTuple(params, "s", &property_name)) {
  429. bool success = false;
  430. if (PyObject_HasAttrString(obj, property_name)) {
  431. if (PyObject_DelAttrString(obj, property_name) != -1) {
  432. success = true;
  433. } else {
  434. PyErr_Clear();
  435. }
  436. }
  437. if (!success) {
  438. if (PyObject_DelItemString(obj, property_name) != -1) {
  439. success = true;
  440. } else {
  441. PyErr_Clear();
  442. }
  443. }
  444. if (success) {
  445. result = Py_True;
  446. } else {
  447. result = Py_False;
  448. }
  449. Py_INCREF(result);
  450. }
  451. } else if (strcmp(method_name, "__get_property__") == 0) {
  452. char *property_name;
  453. if (PyArg_ParseTuple(params, "s", &property_name)) {
  454. bool success = false;
  455. if (PyObject_HasAttrString(obj, property_name)) {
  456. result = PyObject_GetAttrString(obj, property_name);
  457. if (result != NULL) {
  458. success = true;
  459. } else {
  460. PyErr_Clear();
  461. }
  462. }
  463. if (!success) {
  464. if (PyMapping_HasKeyString(obj, property_name)) {
  465. result = PyMapping_GetItemString(obj, property_name);
  466. if (result != NULL) {
  467. success = true;
  468. } else {
  469. PyErr_Clear();
  470. }
  471. }
  472. }
  473. if (!success) {
  474. result = NULL;
  475. }
  476. }
  477. } else if (strcmp(method_name, "__has_method__") == 0) {
  478. char *property_name;
  479. result = Py_False;
  480. if (PyArg_ParseTuple(params, "s", &property_name)) {
  481. if (*property_name) {
  482. // Check for a callable method
  483. if (PyObject_HasAttrString(obj, property_name)) {
  484. PyObject *prop = PyObject_GetAttrString(obj, property_name);
  485. if (PyCallable_Check(prop)) {
  486. result = Py_True;
  487. }
  488. Py_DECREF(prop);
  489. }
  490. } else {
  491. // Check for the default method
  492. if (PyCallable_Check(obj)) {
  493. result = Py_True;
  494. }
  495. }
  496. }
  497. Py_INCREF(result);
  498. } else {
  499. // Not a special-case name. Call the named method.
  500. PyObject *method = PyObject_GetAttrString(obj, (char *)method_name);
  501. if (method != NULL) {
  502. result = PyObject_CallObject(method, params);
  503. Py_DECREF(method);
  504. }
  505. }
  506. Py_DECREF(params);
  507. // Feed the return value back through the XML pipe to the
  508. // caller.
  509. if (result != NULL) {
  510. xresponse->LinkEndChild(pyobj_to_xml(result));
  511. Py_DECREF(result);
  512. } else {
  513. // Print the Python error message if there was one.
  514. PyErr_Print();
  515. }
  516. Py_DECREF(obj);
  517. }
  518. }
  519. }
  520. if (needs_response) {
  521. write_xml(_pipe_write, &doc, nout);
  522. }
  523. }
  524. ////////////////////////////////////////////////////////////////////
  525. // Function: P3DPythonRun::check_comm
  526. // Access: Private
  527. // Description: This method is added to the task manager (via
  528. // st_check_comm, below) so that it gets a call every
  529. // frame. Its job is to check for commands received
  530. // from the plugin host in the parent process.
  531. ////////////////////////////////////////////////////////////////////
  532. void P3DPythonRun::
  533. check_comm() {
  534. // nout << ":";
  535. ACQUIRE_LOCK(_commands_lock);
  536. while (!_commands.empty()) {
  537. TiXmlDocument *doc = _commands.front();
  538. _commands.pop_front();
  539. RELEASE_LOCK(_commands_lock);
  540. handle_command(doc);
  541. ACQUIRE_LOCK(_commands_lock);
  542. }
  543. RELEASE_LOCK(_commands_lock);
  544. if (!_program_continue) {
  545. // The low-level thread detected an error, for instance pipe
  546. // closed. We should exit gracefully.
  547. terminate_session();
  548. }
  549. // Sleep to yield the timeslice, but only if we're not running in
  550. // the main thread.
  551. if (Thread::get_current_thread() != Thread::get_main_thread()) {
  552. Thread::sleep(0.001);
  553. }
  554. }
  555. ////////////////////////////////////////////////////////////////////
  556. // Function: P3DPythonRun::st_check_comm
  557. // Access: Private, Static
  558. // Description: This is a static Python wrapper around py_check_comm,
  559. // needed to add the function to a PythonTask.
  560. ////////////////////////////////////////////////////////////////////
  561. PyObject *P3DPythonRun::
  562. st_check_comm(PyObject *, PyObject *args) {
  563. P3DPythonRun::_global_ptr->check_comm();
  564. return Py_BuildValue("i", AsyncTask::DS_cont);
  565. }
  566. ////////////////////////////////////////////////////////////////////
  567. // Function: P3DPythonRun::wait_script_response
  568. // Access: Private
  569. // Description: This method is similar to check_comm(), above, but
  570. // instead of handling all events, it waits for a
  571. // specific script_response ID to come back from the
  572. // browser, and leaves all other events in the queue.
  573. ////////////////////////////////////////////////////////////////////
  574. TiXmlDocument *P3DPythonRun::
  575. wait_script_response(int response_id) {
  576. // nout << "waiting script_response " << response_id << "\n";
  577. while (true) {
  578. Commands::iterator ci;
  579. // First, walk through the _commands queue to see if there's
  580. // anything that needs immediate processing.
  581. ACQUIRE_LOCK(_commands_lock);
  582. for (ci = _commands.begin(); ci != _commands.end(); ++ci) {
  583. TiXmlDocument *doc = (*ci);
  584. TiXmlElement *xcommand = doc->FirstChildElement("command");
  585. if (xcommand != NULL) {
  586. const char *cmd = xcommand->Attribute("cmd");
  587. if ((cmd != NULL && strcmp(cmd, "script_response") == 0) ||
  588. xcommand->Attribute("want_response_id") != NULL) {
  589. // This is either a response, or it's a command that will
  590. // want a response itself. In either case we should handle
  591. // it right away. ("handling" a response means moving it to
  592. // the _responses queue.)
  593. _commands.erase(ci);
  594. RELEASE_LOCK(_commands_lock);
  595. handle_command(doc);
  596. ACQUIRE_LOCK(_commands_lock);
  597. break;
  598. }
  599. }
  600. }
  601. RELEASE_LOCK(_commands_lock);
  602. // Now, walk through the _responses queue to look for the
  603. // particular response we're waiting for.
  604. _responses_lock.acquire();
  605. for (ci = _responses.begin(); ci != _responses.end(); ++ci) {
  606. TiXmlDocument *doc = (*ci);
  607. TiXmlElement *xcommand = doc->FirstChildElement("command");
  608. assert(xcommand != NULL);
  609. const char *cmd = xcommand->Attribute("cmd");
  610. assert(cmd != NULL && strcmp(cmd, "script_response") == 0);
  611. int unique_id;
  612. if (xcommand->QueryIntAttribute("unique_id", &unique_id) == TIXML_SUCCESS) {
  613. if (unique_id == response_id) {
  614. // This is the response we were waiting for.
  615. _responses.erase(ci);
  616. _responses_lock.release();
  617. // nout << "got script_response " << unique_id << "\n";
  618. return doc;
  619. }
  620. }
  621. }
  622. _responses_lock.release();
  623. if (!_program_continue) {
  624. terminate_session();
  625. }
  626. #ifdef _WIN32
  627. // Make sure we process the Windows event loop while we're
  628. // waiting, or everything that depends on Windows messages will
  629. // starve.
  630. // We appear to be best off with just a single PeekMessage() call
  631. // here; the full message pump seems to cause problems.
  632. MSG msg;
  633. PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE | PM_NOYIELD);
  634. #endif // _WIN32
  635. // nout << ".";
  636. // It hasn't shown up yet. Give the sub-thread a chance to
  637. // process the input and append it to the queue.
  638. Thread::force_yield();
  639. }
  640. assert(false);
  641. }
  642. ////////////////////////////////////////////////////////////////////
  643. // Function: P3DPythonRun::py_request_func
  644. // Access: Private
  645. // Description: This method is a special Python function that is
  646. // added as a callback to the AppRunner class, to allow
  647. // Python to upcall into this object.
  648. ////////////////////////////////////////////////////////////////////
  649. PyObject *P3DPythonRun::
  650. py_request_func(PyObject *args) {
  651. int instance_id;
  652. const char *request_type;
  653. PyObject *extra_args;
  654. if (!PyArg_ParseTuple(args, "isO", &instance_id, &request_type, &extra_args)) {
  655. return NULL;
  656. }
  657. if (strcmp(request_type, "wait_script_response") == 0) {
  658. // This is a special case. Instead of generating a new request,
  659. // this means to wait for a particular script_response to come in
  660. // on the wire.
  661. int response_id;
  662. if (!PyArg_ParseTuple(extra_args, "i", &response_id)) {
  663. return NULL;
  664. }
  665. TiXmlDocument *doc = wait_script_response(response_id);
  666. assert(doc != NULL);
  667. TiXmlElement *xcommand = doc->FirstChildElement("command");
  668. assert(xcommand != NULL);
  669. TiXmlElement *xvalue = xcommand->FirstChildElement("value");
  670. PyObject *value = NULL;
  671. if (xvalue != NULL) {
  672. value = xml_to_pyobj(xvalue);
  673. } else {
  674. // An absence of a <value> element is an exception. We will
  675. // return NULL from this function, but first set the error
  676. // condition.
  677. PyErr_SetString(PyExc_EnvironmentError, "Error on script call");
  678. }
  679. delete doc;
  680. return value;
  681. }
  682. TiXmlDocument doc;
  683. TiXmlElement *xrequest = new TiXmlElement("request");
  684. xrequest->SetAttribute("instance_id", instance_id);
  685. xrequest->SetAttribute("rtype", request_type);
  686. doc.LinkEndChild(xrequest);
  687. if (strcmp(request_type, "notify") == 0) {
  688. // A general notification to be sent directly to the instance.
  689. const char *message;
  690. if (!PyArg_ParseTuple(extra_args, "s", &message)) {
  691. return NULL;
  692. }
  693. xrequest->SetAttribute("message", message);
  694. write_xml(_pipe_write, &doc, nout);
  695. } else if (strcmp(request_type, "script") == 0) {
  696. // Meddling with a scripting variable on the browser side.
  697. const char *operation;
  698. PyObject *object;
  699. const char *property_name;
  700. PyObject *value;
  701. int needs_response;
  702. int unique_id;
  703. if (!PyArg_ParseTuple(extra_args, "sOsOii",
  704. &operation, &object, &property_name, &value,
  705. &needs_response, &unique_id)) {
  706. return NULL;
  707. }
  708. xrequest->SetAttribute("operation", operation);
  709. xrequest->SetAttribute("property_name", property_name);
  710. xrequest->SetAttribute("needs_response", (int)(needs_response != 0));
  711. xrequest->SetAttribute("unique_id", unique_id);
  712. TiXmlElement *xobject = pyobj_to_xml(object);
  713. xobject->SetValue("object");
  714. xrequest->LinkEndChild(xobject);
  715. TiXmlElement *xvalue = pyobj_to_xml(value);
  716. xrequest->LinkEndChild(xvalue);
  717. write_xml(_pipe_write, &doc, nout);
  718. } else if (strcmp(request_type, "drop_p3dobj") == 0) {
  719. // Release a particular P3D_object that we were holding a
  720. // reference to.
  721. int object_id;
  722. if (!PyArg_ParseTuple(extra_args, "i", &object_id)) {
  723. return NULL;
  724. }
  725. xrequest->SetAttribute("object_id", object_id);
  726. write_xml(_pipe_write, &doc, nout);
  727. } else {
  728. string message = string("Unsupported request type: ") + string(request_type);
  729. PyErr_SetString(PyExc_ValueError, message.c_str());
  730. return NULL;
  731. }
  732. return Py_BuildValue("");
  733. }
  734. ////////////////////////////////////////////////////////////////////
  735. // Function: P3DPythonRun::st_request_func
  736. // Access: Private, Static
  737. // Description: This is the static wrapper around py_request_func.
  738. ////////////////////////////////////////////////////////////////////
  739. PyObject *P3DPythonRun::
  740. st_request_func(PyObject *, PyObject *args) {
  741. return P3DPythonRun::_global_ptr->py_request_func(args);
  742. }
  743. ////////////////////////////////////////////////////////////////////
  744. // Function: P3DPythonRun::spawn_read_thread
  745. // Access: Private
  746. // Description: Starts the read thread. This thread is responsible
  747. // for reading the standard input socket for XML
  748. // commands and storing them in the _commands queue.
  749. ////////////////////////////////////////////////////////////////////
  750. void P3DPythonRun::
  751. spawn_read_thread() {
  752. assert(!_read_thread_continue);
  753. // We have to use direct OS calls to create the thread instead of
  754. // Panda constructs, because it has to be an actual thread, not
  755. // necessarily a Panda thread (we can't use Panda's simple threads
  756. // implementation, because we can't get overlapped I/O on an
  757. // anonymous pipe in Windows).
  758. _read_thread_continue = true;
  759. SPAWN_THREAD(_read_thread, rt_thread_run, this);
  760. }
  761. ////////////////////////////////////////////////////////////////////
  762. // Function: P3DPythonRun::join_read_thread
  763. // Access: Private
  764. // Description: Waits for the read thread to stop.
  765. ////////////////////////////////////////////////////////////////////
  766. void P3DPythonRun::
  767. join_read_thread() {
  768. _read_thread_continue = false;
  769. _pipe_read.close();
  770. JOIN_THREAD(_read_thread);
  771. }
  772. ////////////////////////////////////////////////////////////////////
  773. // Function: P3DPythonRun::start_instance
  774. // Access: Private
  775. // Description: Starts the indicated instance running within the
  776. // Python process.
  777. ////////////////////////////////////////////////////////////////////
  778. void P3DPythonRun::
  779. start_instance(P3DCInstance *inst, TiXmlElement *xinstance) {
  780. _instances[inst->get_instance_id()] = inst;
  781. set_instance_info(inst, xinstance);
  782. TiXmlElement *xpackage = xinstance->FirstChildElement("package");
  783. while (xpackage != (TiXmlElement *)NULL) {
  784. add_package_info(inst, xpackage);
  785. xpackage = xpackage->NextSiblingElement("package");
  786. }
  787. TiXmlElement *xfparams = xinstance->FirstChildElement("fparams");
  788. if (xfparams != (TiXmlElement *)NULL) {
  789. set_p3d_filename(inst, xfparams);
  790. }
  791. TiXmlElement *xwparams = xinstance->FirstChildElement("wparams");
  792. if (xwparams != (TiXmlElement *)NULL) {
  793. setup_window(inst, xwparams);
  794. }
  795. }
  796. ////////////////////////////////////////////////////////////////////
  797. // Function: P3DPythonRun::terminate_instance
  798. // Access: Private
  799. // Description: Stops the instance with the indicated id.
  800. ////////////////////////////////////////////////////////////////////
  801. void P3DPythonRun::
  802. terminate_instance(int id) {
  803. Instances::iterator ii = _instances.find(id);
  804. if (ii == _instances.end()) {
  805. nout << "Can't stop instance " << id << ": not started.\n";
  806. return;
  807. }
  808. P3DCInstance *inst = (*ii).second;
  809. _instances.erase(ii);
  810. delete inst;
  811. // TODO: we don't currently have any way to stop just one instance
  812. // of a multi-instance session. This will require a different
  813. // Python interface than ShowBase.
  814. terminate_session();
  815. }
  816. ////////////////////////////////////////////////////////////////////
  817. // Function: P3DPythonRun::set_instance_info
  818. // Access: Private
  819. // Description: Sets some global information about the instance.
  820. ////////////////////////////////////////////////////////////////////
  821. void P3DPythonRun::
  822. set_instance_info(P3DCInstance *inst, TiXmlElement *xinstance) {
  823. const char *root_dir = xinstance->Attribute("root_dir");
  824. if (root_dir == NULL) {
  825. root_dir = "";
  826. }
  827. PyObject *result = PyObject_CallMethod
  828. (_runner, (char *)"setInstanceInfo", (char *)"s", root_dir);
  829. if (result == NULL) {
  830. PyErr_Print();
  831. }
  832. Py_XDECREF(result);
  833. }
  834. ////////////////////////////////////////////////////////////////////
  835. // Function: P3DPythonRun::add_package_info
  836. // Access: Private
  837. // Description: Adds some information about a pre-loaded package.
  838. ////////////////////////////////////////////////////////////////////
  839. void P3DPythonRun::
  840. add_package_info(P3DCInstance *inst, TiXmlElement *xpackage) {
  841. const char *name = xpackage->Attribute("name");
  842. const char *platform = xpackage->Attribute("platform");
  843. const char *version = xpackage->Attribute("version");
  844. const char *host = xpackage->Attribute("host");
  845. if (name == NULL || version == NULL || host == NULL) {
  846. return;
  847. }
  848. if (platform == NULL) {
  849. platform = "";
  850. }
  851. PyObject *result = PyObject_CallMethod
  852. (_runner, (char *)"addPackageInfo", (char *)"ssss",
  853. name, platform, version, host);
  854. if (result == NULL) {
  855. PyErr_Print();
  856. }
  857. Py_XDECREF(result);
  858. }
  859. ////////////////////////////////////////////////////////////////////
  860. // Function: P3DPythonRun::set_p3d_filename
  861. // Access: Private
  862. // Description: Sets the startup filename and tokens for the
  863. // indicated instance.
  864. ////////////////////////////////////////////////////////////////////
  865. void P3DPythonRun::
  866. set_p3d_filename(P3DCInstance *inst, TiXmlElement *xfparams) {
  867. string p3d_filename;
  868. const char *p3d_filename_c = xfparams->Attribute("p3d_filename");
  869. if (p3d_filename_c != NULL) {
  870. p3d_filename = p3d_filename_c;
  871. }
  872. PyObject *token_list = PyList_New(0);
  873. TiXmlElement *xtoken = xfparams->FirstChildElement("token");
  874. while (xtoken != NULL) {
  875. string keyword, value;
  876. const char *keyword_c = xtoken->Attribute("keyword");
  877. if (keyword_c != NULL) {
  878. keyword = keyword_c;
  879. }
  880. const char *value_c = xtoken->Attribute("value");
  881. if (value_c != NULL) {
  882. value = value_c;
  883. }
  884. PyObject *tuple = Py_BuildValue("(ss)", keyword.c_str(),
  885. value.c_str());
  886. PyList_Append(token_list, tuple);
  887. Py_DECREF(tuple);
  888. xtoken = xtoken->NextSiblingElement("token");
  889. }
  890. PyObject *arg_list = PyList_New(0);
  891. TiXmlElement *xarg = xfparams->FirstChildElement("arg");
  892. while (xarg != NULL) {
  893. string value;
  894. const char *value_c = xarg->Attribute("value");
  895. if (value_c != NULL) {
  896. value = value_c;
  897. }
  898. PyObject *str = Py_BuildValue("s", value.c_str());
  899. PyList_Append(arg_list, str);
  900. Py_DECREF(str);
  901. xarg = xarg->NextSiblingElement("arg");
  902. }
  903. PyObject *result = PyObject_CallMethod
  904. (_runner, (char *)"setP3DFilename", (char *)"sOOi", p3d_filename.c_str(),
  905. token_list, arg_list, inst->get_instance_id());
  906. Py_DECREF(token_list);
  907. Py_DECREF(arg_list);
  908. if (result == NULL) {
  909. PyErr_Print();
  910. }
  911. Py_XDECREF(result);
  912. }
  913. ////////////////////////////////////////////////////////////////////
  914. // Function: P3DPythonRun::setup_window
  915. // Access: Private
  916. // Description: Sets the window parameters for the indicated instance.
  917. ////////////////////////////////////////////////////////////////////
  918. void P3DPythonRun::
  919. setup_window(int id, TiXmlElement *xwparams) {
  920. Instances::iterator ii = _instances.find(id);
  921. if (ii == _instances.end()) {
  922. nout << "Can't setup window for " << id << ": not started.\n";
  923. return;
  924. }
  925. P3DCInstance *inst = (*ii).second;
  926. setup_window(inst, xwparams);
  927. }
  928. ////////////////////////////////////////////////////////////////////
  929. // Function: P3DPythonRun::setup_window
  930. // Access: Private
  931. // Description: Sets the window parameters for the indicated instance.
  932. ////////////////////////////////////////////////////////////////////
  933. void P3DPythonRun::
  934. setup_window(P3DCInstance *inst, TiXmlElement *xwparams) {
  935. string window_type;
  936. const char *window_type_c = xwparams->Attribute("window_type");
  937. if (window_type_c != NULL) {
  938. window_type = window_type_c;
  939. }
  940. int win_x, win_y, win_width, win_height;
  941. xwparams->Attribute("win_x", &win_x);
  942. xwparams->Attribute("win_y", &win_y);
  943. xwparams->Attribute("win_width", &win_width);
  944. xwparams->Attribute("win_height", &win_height);
  945. long parent_window_handle = 0;
  946. const char *subprocess_window = "";
  947. #ifdef _WIN32
  948. int hwnd;
  949. if (xwparams->Attribute("parent_hwnd", &hwnd)) {
  950. parent_window_handle = (long)hwnd;
  951. }
  952. #elif __APPLE__
  953. // On Mac, we don't parent windows directly to the browser; instead,
  954. // we have to go through this subprocess-window nonsense.
  955. subprocess_window = xwparams->Attribute("subprocess_window");
  956. if (subprocess_window == NULL) {
  957. subprocess_window = "";
  958. }
  959. #elif defined(HAVE_X11)
  960. // Use stringstream to decode the "long" attribute.
  961. const char *parent_cstr = xwparams->Attribute("parent_xwindow");
  962. if (parent_cstr != NULL) {
  963. istringstream strm(parent_cstr);
  964. strm >> parent_window_handle;
  965. }
  966. #endif
  967. // TODO: direct this into the particular instance. This will
  968. // require a specialized ShowBase replacement.
  969. PyObject *result = PyObject_CallMethod
  970. (_runner, (char *)"setupWindow", (char *)"siiiiis", window_type.c_str(),
  971. win_x, win_y, win_width, win_height,
  972. parent_window_handle, subprocess_window);
  973. if (result == NULL) {
  974. PyErr_Print();
  975. }
  976. Py_XDECREF(result);
  977. }
  978. ////////////////////////////////////////////////////////////////////
  979. // Function: P3DPythonRun::terminate_session
  980. // Access: Private
  981. // Description: Stops all currently-running instances.
  982. ////////////////////////////////////////////////////////////////////
  983. void P3DPythonRun::
  984. terminate_session() {
  985. Instances::iterator ii;
  986. for (ii = _instances.begin(); ii != _instances.end(); ++ii) {
  987. P3DCInstance *inst = (*ii).second;
  988. delete inst;
  989. }
  990. _instances.clear();
  991. PyObject *result = PyObject_CallMethod(_taskMgr, (char *)"stop", (char *)"");
  992. if (result == NULL) {
  993. PyErr_Print();
  994. return;
  995. }
  996. Py_DECREF(result);
  997. // The task manager is cleaned up. Let's exit immediately here,
  998. // rather than returning all the way up. This just makes it easier
  999. // when we call terminate_session() from a deeply-nested loop.
  1000. exit(0);
  1001. }
  1002. ////////////////////////////////////////////////////////////////////
  1003. // Function: P3DPythonRun::pyobj_to_xml
  1004. // Access: Private
  1005. // Description: Converts the indicated PyObject to the appropriate
  1006. // XML representation of a P3D_value type, and returns a
  1007. // freshly-allocated TiXmlElement.
  1008. ////////////////////////////////////////////////////////////////////
  1009. TiXmlElement *P3DPythonRun::
  1010. pyobj_to_xml(PyObject *value) {
  1011. TiXmlElement *xvalue = new TiXmlElement("value");
  1012. if (value == Py_None) {
  1013. // None.
  1014. xvalue->SetAttribute("type", "none");
  1015. } else if (PyBool_Check(value)) {
  1016. // A bool value.
  1017. xvalue->SetAttribute("type", "bool");
  1018. xvalue->SetAttribute("value", PyObject_IsTrue(value));
  1019. } else if (PyInt_Check(value)) {
  1020. // A plain integer value.
  1021. xvalue->SetAttribute("type", "int");
  1022. xvalue->SetAttribute("value", PyInt_AsLong(value));
  1023. } else if (PyLong_Check(value)) {
  1024. // A long integer value. This gets converted either as an integer
  1025. // or as a floating-point type, whichever fits.
  1026. long lvalue = PyLong_AsLong(value);
  1027. if (PyErr_Occurred()) {
  1028. // It won't fit as an integer; make it a double.
  1029. PyErr_Clear();
  1030. xvalue->SetAttribute("type", "float");
  1031. xvalue->SetDoubleAttribute("value", PyLong_AsDouble(value));
  1032. } else {
  1033. // It fits as an integer.
  1034. xvalue->SetAttribute("type", "int");
  1035. xvalue->SetAttribute("value", lvalue);
  1036. }
  1037. } else if (PyFloat_Check(value)) {
  1038. // A floating-point value.
  1039. xvalue->SetAttribute("type", "float");
  1040. xvalue->SetDoubleAttribute("value", PyFloat_AsDouble(value));
  1041. } else if (PyUnicode_Check(value)) {
  1042. // A unicode value. Convert to utf-8 for the XML encoding.
  1043. xvalue->SetAttribute("type", "string");
  1044. PyObject *as_str = PyUnicode_AsUTF8String(value);
  1045. if (as_str != NULL) {
  1046. char *buffer;
  1047. Py_ssize_t length;
  1048. if (PyString_AsStringAndSize(as_str, &buffer, &length) != -1) {
  1049. string str(buffer, length);
  1050. xvalue->SetAttribute("value", str);
  1051. }
  1052. Py_DECREF(as_str);
  1053. }
  1054. } else if (PyString_Check(value)) {
  1055. // A string value.
  1056. xvalue->SetAttribute("type", "string");
  1057. char *buffer;
  1058. Py_ssize_t length;
  1059. if (PyString_AsStringAndSize(value, &buffer, &length) != -1) {
  1060. string str(buffer, length);
  1061. xvalue->SetAttribute("value", str);
  1062. }
  1063. } else if (PyTuple_Check(value)) {
  1064. // An immutable sequence. Pass it as a concrete.
  1065. xvalue->SetAttribute("type", "concrete_sequence");
  1066. Py_ssize_t length = PySequence_Length(value);
  1067. for (Py_ssize_t i = 0; i < length; ++i) {
  1068. PyObject *item = PySequence_GetItem(value, i);
  1069. if (item != NULL) {
  1070. xvalue->LinkEndChild(pyobj_to_xml(item));
  1071. Py_DECREF(item);
  1072. }
  1073. }
  1074. } else if (PyObject_IsInstance(value, _concrete_struct_class)) {
  1075. // This is a ConcreteStruct.
  1076. xvalue->SetAttribute("type", "concrete_struct");
  1077. PyObject *items = PyObject_CallMethod(value, (char *)"getConcreteProperties", (char *)"");
  1078. if (items == NULL) {
  1079. PyErr_Print();
  1080. return xvalue;
  1081. }
  1082. Py_ssize_t length = PySequence_Length(items);
  1083. for (Py_ssize_t i = 0; i < length; ++i) {
  1084. PyObject *item = PySequence_GetItem(items, i);
  1085. if (item != NULL) {
  1086. PyObject *a = PySequence_GetItem(item, 0);
  1087. if (a != NULL) {
  1088. PyObject *b = PySequence_GetItem(item, 1);
  1089. if (b != NULL) {
  1090. TiXmlElement *xitem = pyobj_to_xml(b);
  1091. Py_DECREF(b);
  1092. PyObject *as_str;
  1093. if (PyUnicode_Check(a)) {
  1094. // The key is a unicode value.
  1095. as_str = PyUnicode_AsUTF8String(a);
  1096. } else {
  1097. // The key is a string value or something else. Make it
  1098. // a string.
  1099. as_str = PyObject_Str(a);
  1100. }
  1101. char *buffer;
  1102. Py_ssize_t length;
  1103. if (PyString_AsStringAndSize(as_str, &buffer, &length) != -1) {
  1104. string str(buffer, length);
  1105. xitem->SetAttribute("key", str);
  1106. }
  1107. Py_DECREF(as_str);
  1108. xvalue->LinkEndChild(xitem);
  1109. }
  1110. Py_DECREF(a);
  1111. }
  1112. Py_DECREF(item);
  1113. }
  1114. }
  1115. // We've already avoided errors in the above code; clear the error
  1116. // flag.
  1117. PyErr_Clear();
  1118. Py_DECREF(items);
  1119. } else if (PyObject_IsInstance(value, _undefined_object_class)) {
  1120. // This is an UndefinedObject.
  1121. xvalue->SetAttribute("type", "undefined");
  1122. } else if (PyObject_IsInstance(value, _browser_object_class)) {
  1123. // This is a BrowserObject, a reference to an object that actually
  1124. // exists in the host namespace. So, pass up the appropriate
  1125. // object ID.
  1126. PyObject *objectId = PyObject_GetAttrString(value, (char *)"_BrowserObject__objectId");
  1127. if (objectId != NULL) {
  1128. int object_id = PyInt_AsLong(objectId);
  1129. xvalue->SetAttribute("type", "browser");
  1130. xvalue->SetAttribute("object_id", object_id);
  1131. Py_DECREF(objectId);
  1132. }
  1133. } else {
  1134. // Some other kind of object. Make it a generic Python object.
  1135. // This is more expensive for the caller to deal with--it requires
  1136. // a back-and-forth across the XML pipe--but it's much more
  1137. // general.
  1138. int object_id = _next_sent_id;
  1139. ++_next_sent_id;
  1140. bool inserted = _sent_objects.insert(SentObjects::value_type(object_id, value)).second;
  1141. while (!inserted) {
  1142. // Hmm, we must have cycled around the entire int space? Either
  1143. // that, or there's a logic bug somewhere. Assume the former,
  1144. // and keep looking for an empty slot.
  1145. object_id = _next_sent_id;
  1146. ++_next_sent_id;
  1147. inserted = _sent_objects.insert(SentObjects::value_type(object_id, value)).second;
  1148. }
  1149. // Now that it's stored in the map, increment its reference count.
  1150. Py_INCREF(value);
  1151. xvalue->SetAttribute("type", "python");
  1152. xvalue->SetAttribute("object_id", object_id);
  1153. }
  1154. return xvalue;
  1155. }
  1156. ////////////////////////////////////////////////////////////////////
  1157. // Function: P3DPythonRun::xml_to_pyobj
  1158. // Access: Private
  1159. // Description: Converts the XML representation of a P3D_value type
  1160. // into the equivalent Python object and returns it.
  1161. ////////////////////////////////////////////////////////////////////
  1162. PyObject *P3DPythonRun::
  1163. xml_to_pyobj(TiXmlElement *xvalue) {
  1164. const char *type = xvalue->Attribute("type");
  1165. if (strcmp(type, "none") == 0) {
  1166. return Py_BuildValue("");
  1167. } else if (strcmp(type, "bool") == 0) {
  1168. int value;
  1169. if (xvalue->QueryIntAttribute("value", &value) == TIXML_SUCCESS) {
  1170. return PyBool_FromLong(value);
  1171. }
  1172. } else if (strcmp(type, "int") == 0) {
  1173. int value;
  1174. if (xvalue->QueryIntAttribute("value", &value) == TIXML_SUCCESS) {
  1175. return PyInt_FromLong(value);
  1176. }
  1177. } else if (strcmp(type, "float") == 0) {
  1178. double value;
  1179. if (xvalue->QueryDoubleAttribute("value", &value) == TIXML_SUCCESS) {
  1180. return PyFloat_FromDouble(value);
  1181. }
  1182. } else if (strcmp(type, "string") == 0) {
  1183. // Using the string form here instead of the char * form, so we
  1184. // don't get tripped up on embedded null characters.
  1185. const string *value = xvalue->Attribute(string("value"));
  1186. if (value != NULL) {
  1187. return PyString_FromStringAndSize(value->data(), value->length());
  1188. }
  1189. } else if (strcmp(type, "undefined") == 0) {
  1190. Py_INCREF(_undefined);
  1191. return _undefined;
  1192. } else if (strcmp(type, "browser") == 0) {
  1193. int object_id;
  1194. if (xvalue->QueryIntAttribute("object_id", &object_id) == TIXML_SUCCESS) {
  1195. // Construct a new BrowserObject wrapper around this object.
  1196. return PyObject_CallFunction(_browser_object_class, (char *)"Oi",
  1197. _runner, object_id);
  1198. }
  1199. } else if (strcmp(type, "concrete_sequence") == 0) {
  1200. // Receive a concrete sequence as a tuple.
  1201. PyObject *list = PyList_New(0);
  1202. TiXmlElement *xitem = xvalue->FirstChildElement("value");
  1203. while (xitem != NULL) {
  1204. PyObject *item = xml_to_pyobj(xitem);
  1205. if (item != NULL) {
  1206. PyList_Append(list, item);
  1207. Py_DECREF(item);
  1208. }
  1209. xitem = xitem->NextSiblingElement("value");
  1210. }
  1211. PyObject *result = PyList_AsTuple(list);
  1212. Py_DECREF(list);
  1213. return result;
  1214. } else if (strcmp(type, "concrete_struct") == 0) {
  1215. // Receive a concrete struct as a new ConcreteStruct instance.
  1216. PyObject *obj = PyObject_CallFunction(_concrete_struct_class, (char *)"");
  1217. if (obj != NULL) {
  1218. TiXmlElement *xitem = xvalue->FirstChildElement("value");
  1219. while (xitem != NULL) {
  1220. const char *key = xitem->Attribute("key");
  1221. if (key != NULL) {
  1222. PyObject *item = xml_to_pyobj(xitem);
  1223. if (item != NULL) {
  1224. PyObject_SetAttrString(obj, (char *)key, item);
  1225. Py_DECREF(item);
  1226. }
  1227. }
  1228. xitem = xitem->NextSiblingElement("value");
  1229. }
  1230. return obj;
  1231. }
  1232. } else if (strcmp(type, "python") == 0) {
  1233. int object_id;
  1234. if (xvalue->QueryIntAttribute("object_id", &object_id) == TIXML_SUCCESS) {
  1235. SentObjects::iterator si = _sent_objects.find(object_id);
  1236. PyObject *result;
  1237. if (si == _sent_objects.end()) {
  1238. // Hmm, the parent process gave us a bogus object ID.
  1239. result = _undefined;
  1240. } else {
  1241. result = (*si).second;
  1242. }
  1243. Py_INCREF(result);
  1244. return result;
  1245. }
  1246. }
  1247. // Something went wrong in decoding.
  1248. PyObject *result = _undefined;
  1249. Py_INCREF(result);
  1250. return result;
  1251. }
  1252. ////////////////////////////////////////////////////////////////////
  1253. // Function: P3DPythonRun::rt_thread_run
  1254. // Access: Private
  1255. // Description: The main function for the read thread.
  1256. ////////////////////////////////////////////////////////////////////
  1257. void P3DPythonRun::
  1258. rt_thread_run() {
  1259. while (_read_thread_continue) {
  1260. TiXmlDocument *doc = read_xml(_pipe_read, nout);
  1261. if (doc == NULL) {
  1262. // Some error on reading. Abort.
  1263. _program_continue = false;
  1264. return;
  1265. }
  1266. // Successfully read an XML document.
  1267. // Check for one special case: the "exit" command means we shut
  1268. // down the read thread along with everything else.
  1269. TiXmlElement *xcommand = doc->FirstChildElement("command");
  1270. if (xcommand != NULL) {
  1271. const char *cmd = xcommand->Attribute("cmd");
  1272. if (cmd != NULL) {
  1273. if (strcmp(cmd, "exit") == 0) {
  1274. _read_thread_continue = false;
  1275. }
  1276. }
  1277. }
  1278. // Feed the command up to the parent.
  1279. ACQUIRE_LOCK(_commands_lock);
  1280. _commands.push_back(doc);
  1281. RELEASE_LOCK(_commands_lock);
  1282. }
  1283. }
  1284. ////////////////////////////////////////////////////////////////////
  1285. // Function: main
  1286. // Description: Starts the program running.
  1287. ////////////////////////////////////////////////////////////////////
  1288. int
  1289. main(int argc, char *argv[]) {
  1290. P3DPythonRun::_global_ptr = new P3DPythonRun(argc, argv);
  1291. if (!P3DPythonRun::_global_ptr->run_python()) {
  1292. nout << "Couldn't initialize Python.\n";
  1293. return 1;
  1294. }
  1295. return 0;
  1296. }