p3dPythonRun.cxx 46 KB

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