p3dPythonRun.cxx 46 KB

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