p3dPythonRun.cxx 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086
  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. // There is only one P3DPythonRun object in any given process space.
  17. // Makes the statics easier to deal with, and we don't need multiple
  18. // instances of this think.
  19. P3DPythonRun *P3DPythonRun::_global_ptr = NULL;
  20. ////////////////////////////////////////////////////////////////////
  21. // Function: P3DPythonRun::Constructor
  22. // Access: Public
  23. // Description:
  24. ////////////////////////////////////////////////////////////////////
  25. P3DPythonRun::
  26. P3DPythonRun(int argc, char *argv[]) {
  27. _read_thread_continue = false;
  28. _program_continue = true;
  29. INIT_LOCK(_commands_lock);
  30. INIT_THREAD(_read_thread);
  31. _program_name = argv[0];
  32. _py_argc = 1;
  33. _py_argv = (char **)malloc(2 * sizeof(char *));
  34. _py_argv[0] = argv[0];
  35. _py_argv[1] = NULL;
  36. // Initialize Python. It appears to be important to do this before
  37. // we open the pipe streams and spawn the thread, below.
  38. Py_SetProgramName((char *)_program_name.c_str());
  39. Py_Initialize();
  40. PySys_SetArgv(_py_argc, _py_argv);
  41. // Open the pipe streams with the input and output handles from the
  42. // parent.
  43. #ifdef _WIN32
  44. HANDLE read = GetStdHandle(STD_INPUT_HANDLE);
  45. HANDLE write = GetStdHandle(STD_OUTPUT_HANDLE);
  46. if (!SetStdHandle(STD_INPUT_HANDLE, INVALID_HANDLE_VALUE)) {
  47. nout << "unable to reset input handle\n";
  48. }
  49. if (!SetStdHandle(STD_OUTPUT_HANDLE, INVALID_HANDLE_VALUE)) {
  50. nout << "unable to reset input handle\n";
  51. }
  52. _pipe_read.open_read(read);
  53. _pipe_write.open_write(write);
  54. #else
  55. _pipe_read.open_read(STDIN_FILENO);
  56. _pipe_write.open_write(STDOUT_FILENO);
  57. #endif // _WIN32
  58. if (!_pipe_read) {
  59. nout << "unable to open read pipe\n";
  60. }
  61. if (!_pipe_write) {
  62. nout << "unable to open write pipe\n";
  63. }
  64. spawn_read_thread();
  65. }
  66. ////////////////////////////////////////////////////////////////////
  67. // Function: P3DPythonRun::Destructor
  68. // Access: Public
  69. // Description:
  70. ////////////////////////////////////////////////////////////////////
  71. P3DPythonRun::
  72. ~P3DPythonRun() {
  73. Py_Finalize();
  74. join_read_thread();
  75. DESTROY_LOCK(_commands_lock);
  76. }
  77. ////////////////////////////////////////////////////////////////////
  78. // Function: P3DPythonRun::run_python
  79. // Access: Public
  80. // Description: Runs the embedded Python process. This method does
  81. // not return until the plugin is ready to exit.
  82. ////////////////////////////////////////////////////////////////////
  83. bool P3DPythonRun::
  84. run_python() {
  85. // First, load runp3d_frozen.pyd. Since this is a magic frozen pyd,
  86. // importing it automatically makes all of its frozen contents
  87. // available to import as well.
  88. PyObject *runp3d_frozen = PyImport_ImportModule("runp3d_frozen");
  89. if (runp3d_frozen == NULL) {
  90. PyErr_Print();
  91. return false;
  92. }
  93. Py_DECREF(runp3d_frozen);
  94. // So now we can import the module itself.
  95. PyObject *runp3d = PyImport_ImportModule("direct.showutil.runp3d");
  96. if (runp3d == NULL) {
  97. PyErr_Print();
  98. return false;
  99. }
  100. // Get the pointers to the objects needed within the module.
  101. PyObject *app_runner_class = PyObject_GetAttrString(runp3d, "AppRunner");
  102. if (app_runner_class == NULL) {
  103. PyErr_Print();
  104. return false;
  105. }
  106. // Construct an instance of AppRunner.
  107. _runner = PyObject_CallFunction(app_runner_class, (char *)"");
  108. if (_runner == NULL) {
  109. PyErr_Print();
  110. return false;
  111. }
  112. Py_DECREF(app_runner_class);
  113. // Get the UndefinedObject class.
  114. _undefined_object_class = PyObject_GetAttrString(runp3d, "UndefinedObject");
  115. if (_undefined_object_class == NULL) {
  116. PyErr_Print();
  117. return false;
  118. }
  119. // And the "Undefined" instance.
  120. _undefined = PyObject_GetAttrString(runp3d, "Undefined");
  121. if (_undefined == NULL) {
  122. PyErr_Print();
  123. return false;
  124. }
  125. // Get the BrowserObject class.
  126. _browser_object_class = PyObject_GetAttrString(runp3d, "BrowserObject");
  127. if (_browser_object_class == NULL) {
  128. PyErr_Print();
  129. return false;
  130. }
  131. // Get the global TaskManager.
  132. _taskMgr = PyObject_GetAttrString(runp3d, "taskMgr");
  133. if (_taskMgr == NULL) {
  134. PyErr_Print();
  135. return false;
  136. }
  137. Py_DECREF(runp3d);
  138. // Construct a Python wrapper around our request_func() method.
  139. static PyMethodDef p3dpython_methods[] = {
  140. {"request_func", P3DPythonRun::st_request_func, METH_VARARGS,
  141. "Send an asynchronous request to the plugin host"},
  142. {NULL, NULL, 0, NULL} /* Sentinel */
  143. };
  144. PyObject *p3dpython = Py_InitModule("p3dpython", p3dpython_methods);
  145. if (p3dpython == NULL) {
  146. PyErr_Print();
  147. return false;
  148. }
  149. PyObject *request_func = PyObject_GetAttrString(p3dpython, "request_func");
  150. if (request_func == NULL) {
  151. PyErr_Print();
  152. return false;
  153. }
  154. // Now pass that func pointer back to our AppRunner instance, so it
  155. // can call up to us.
  156. PyObject *result = PyObject_CallMethod(_runner, (char *)"setRequestFunc", (char *)"O", request_func);
  157. if (result == NULL) {
  158. PyErr_Print();
  159. return false;
  160. }
  161. Py_DECREF(result);
  162. Py_DECREF(request_func);
  163. // Now add check_comm() as a task.
  164. _check_comm_task = new GenericAsyncTask("check_comm", task_check_comm, this);
  165. AsyncTaskManager *task_mgr = AsyncTaskManager::get_global_ptr();
  166. task_mgr->add(_check_comm_task);
  167. // Finally, get lost in taskMgr.run().
  168. PyObject *done = PyObject_CallMethod(_taskMgr, (char *)"run", (char *)"");
  169. if (done == NULL) {
  170. PyErr_Print();
  171. return false;
  172. }
  173. Py_DECREF(done);
  174. return true;
  175. }
  176. ////////////////////////////////////////////////////////////////////
  177. // Function: P3DPythonRun::handle_command
  178. // Access: Private
  179. // Description: Handles a command received from the plugin host, via
  180. // an XML syntax on the wire.
  181. ////////////////////////////////////////////////////////////////////
  182. void P3DPythonRun::
  183. handle_command(TiXmlDocument *doc) {
  184. nout << "received: " << *doc << "\n" << flush;
  185. TiXmlElement *xcommand = doc->FirstChildElement("command");
  186. if (xcommand != NULL) {
  187. bool needs_response = false;
  188. int want_response_id;
  189. if (xcommand->QueryIntAttribute("want_response_id", &want_response_id) == TIXML_SUCCESS) {
  190. // This command will be waiting for a response.
  191. needs_response = true;
  192. }
  193. const char *cmd = xcommand->Attribute("cmd");
  194. if (cmd != NULL) {
  195. if (strcmp(cmd, "start_instance") == 0) {
  196. assert(!needs_response);
  197. TiXmlElement *xinstance = xcommand->FirstChildElement("instance");
  198. if (xinstance != (TiXmlElement *)NULL) {
  199. P3DCInstance *inst = new P3DCInstance(xinstance);
  200. start_instance(inst, xinstance);
  201. }
  202. } else if (strcmp(cmd, "terminate_instance") == 0) {
  203. assert(!needs_response);
  204. int instance_id;
  205. if (xcommand->QueryIntAttribute("instance_id", &instance_id) == TIXML_SUCCESS) {
  206. terminate_instance(instance_id);
  207. }
  208. } else if (strcmp(cmd, "setup_window") == 0) {
  209. assert(!needs_response);
  210. int instance_id;
  211. TiXmlElement *xwparams = xcommand->FirstChildElement("wparams");
  212. if (xwparams != (TiXmlElement *)NULL &&
  213. xcommand->QueryIntAttribute("instance_id", &instance_id) == TIXML_SUCCESS) {
  214. setup_window(instance_id, xwparams);
  215. }
  216. } else if (strcmp(cmd, "exit") == 0) {
  217. assert(!needs_response);
  218. terminate_session();
  219. } else if (strcmp(cmd, "pyobj") == 0) {
  220. // Manipulate or query a python object.
  221. handle_pyobj_command(xcommand, needs_response, want_response_id);
  222. } else if (strcmp(cmd, "script_response") == 0) {
  223. // Response from a script request.
  224. assert(!needs_response);
  225. nout << "Ignoring unexpected script_response\n";
  226. } else {
  227. nout << "Unhandled command " << cmd << "\n";
  228. if (needs_response) {
  229. // Better send a response.
  230. TiXmlDocument doc;
  231. TiXmlDeclaration *decl = new TiXmlDeclaration("1.0", "utf-8", "");
  232. TiXmlElement *xresponse = new TiXmlElement("response");
  233. xresponse->SetAttribute("response_id", want_response_id);
  234. doc.LinkEndChild(decl);
  235. doc.LinkEndChild(xresponse);
  236. nout << "sent: " << doc << "\n" << flush;
  237. _pipe_write << doc << flush;
  238. }
  239. }
  240. }
  241. }
  242. }
  243. ////////////////////////////////////////////////////////////////////
  244. // Function: P3DPythonRun::handle_pyobj_command
  245. // Access: Private
  246. // Description: Handles the pyobj command, which queries or modifies
  247. // a Python object from the browser scripts.
  248. ////////////////////////////////////////////////////////////////////
  249. void P3DPythonRun::
  250. handle_pyobj_command(TiXmlElement *xcommand, bool needs_response,
  251. int want_response_id) {
  252. TiXmlDocument doc;
  253. TiXmlDeclaration *decl = new TiXmlDeclaration("1.0", "utf-8", "");
  254. TiXmlElement *xresponse = new TiXmlElement("response");
  255. xresponse->SetAttribute("response_id", want_response_id);
  256. doc.LinkEndChild(decl);
  257. doc.LinkEndChild(xresponse);
  258. const char *op = xcommand->Attribute("op");
  259. if (op != NULL) {
  260. if (strcmp(op, "get_panda_script_object") == 0) {
  261. // Get Panda's toplevel Python object.
  262. PyObject *obj = PyObject_CallMethod(_runner, "getPandaScriptObject", (char *)"");
  263. if (obj != NULL) {
  264. xresponse->LinkEndChild(pyobj_to_xml(obj));
  265. Py_DECREF(obj);
  266. }
  267. } else if (strcmp(op, "set_browser_script_object") == 0) {
  268. // Set the Browser's toplevel window object.
  269. PyObject *obj;
  270. TiXmlElement *xvalue = xcommand->FirstChildElement("value");
  271. if (xvalue != NULL) {
  272. obj = xml_to_pyobj(xvalue);
  273. } else {
  274. obj = Py_None;
  275. Py_INCREF(obj);
  276. }
  277. PyObject *result = PyObject_CallMethod
  278. (_runner, (char *)"setBrowserScriptObject", (char *)"O", obj);
  279. Py_DECREF(obj);
  280. Py_XDECREF(result);
  281. } else if (strcmp(op, "call") == 0) {
  282. // Call the named method on the indicated object, or the object
  283. // itself if method_name isn't given.
  284. int object_id;
  285. if (xcommand->QueryIntAttribute("object_id", &object_id) == TIXML_SUCCESS) {
  286. PyObject *obj = (PyObject *)(void *)object_id;
  287. const char *method_name = xcommand->Attribute("method_name");
  288. // Build up a list of params.
  289. PyObject *list = PyList_New(0);
  290. TiXmlElement *xchild = xcommand->FirstChildElement("value");
  291. while (xchild != NULL) {
  292. PyObject *child = xml_to_pyobj(xchild);
  293. PyList_Append(list, child);
  294. Py_DECREF(child);
  295. xchild = xchild->NextSiblingElement("value");
  296. }
  297. // Convert the list to a tuple for the call.
  298. PyObject *params = PyList_AsTuple(list);
  299. Py_DECREF(list);
  300. // Now call the method.
  301. PyObject *result = NULL;
  302. if (method_name == NULL) {
  303. // No method name; call the object directly.
  304. result = PyObject_CallObject(obj, params);
  305. // Several special-case "method" names.
  306. } else if (strcmp(method_name, "__bool__") == 0) {
  307. result = PyBool_FromLong(PyObject_IsTrue(obj));
  308. } else if (strcmp(method_name, "__int__") == 0) {
  309. result = PyNumber_Int(obj);
  310. } else if (strcmp(method_name, "__float__") == 0) {
  311. result = PyNumber_Float(obj);
  312. } else if (strcmp(method_name, "__repr__") == 0) {
  313. result = PyObject_Repr(obj);
  314. } else if (strcmp(method_name, "__str__") == 0 ||
  315. strcmp(method_name, "toString") == 0) {
  316. result = PyObject_Str(obj);
  317. } else if (strcmp(method_name, "__setattr__") == 0) {
  318. char *property_name;
  319. PyObject *value;
  320. if (PyArg_ParseTuple(params, "sO", &property_name, &value)) {
  321. PyObject_SetAttrString(obj, property_name, value);
  322. result = Py_True;
  323. Py_INCREF(result);
  324. }
  325. } else if (strcmp(method_name, "__delattr__") == 0) {
  326. char *property_name;
  327. if (PyArg_ParseTuple(params, "s", &property_name)) {
  328. if (PyObject_HasAttrString(obj, property_name)) {
  329. PyObject_DelAttrString(obj, property_name);
  330. result = Py_True;
  331. } else {
  332. result = Py_False;
  333. }
  334. Py_INCREF(result);
  335. }
  336. } else if (strcmp(method_name, "__getattr__") == 0) {
  337. char *property_name;
  338. if (PyArg_ParseTuple(params, "s", &property_name)) {
  339. if (PyObject_HasAttrString(obj, property_name)) {
  340. result = PyObject_GetAttrString(obj, property_name);
  341. } else {
  342. result = NULL;
  343. }
  344. }
  345. } else {
  346. // Not a special-case name. Call the named method.
  347. PyObject *method = PyObject_GetAttrString(obj, (char *)method_name);
  348. if (method != NULL) {
  349. result = PyObject_CallObject(method, params);
  350. Py_DECREF(method);
  351. }
  352. }
  353. Py_DECREF(params);
  354. // Feed the return value back through the XML pipe to the
  355. // caller.
  356. if (result != NULL) {
  357. xresponse->LinkEndChild(pyobj_to_xml(result));
  358. Py_DECREF(result);
  359. }
  360. }
  361. }
  362. }
  363. if (needs_response) {
  364. nout << "sent: " << doc << "\n" << flush;
  365. _pipe_write << doc << flush;
  366. }
  367. }
  368. ////////////////////////////////////////////////////////////////////
  369. // Function: P3DPythonRun::check_comm
  370. // Access: Private
  371. // Description: This method is added to the task manager (via
  372. // task_check_comm, below) so that it gets a call every
  373. // frame. Its job is to check for commands received
  374. // from the plugin host in the parent process.
  375. ////////////////////////////////////////////////////////////////////
  376. void P3DPythonRun::
  377. check_comm() {
  378. ACQUIRE_LOCK(_commands_lock);
  379. while (!_commands.empty()) {
  380. TiXmlDocument *doc = _commands.front();
  381. _commands.pop_front();
  382. assert(_commands.size() < 10);
  383. RELEASE_LOCK(_commands_lock);
  384. handle_command(doc);
  385. delete doc;
  386. ACQUIRE_LOCK(_commands_lock);
  387. }
  388. if (!_program_continue) {
  389. // The low-level thread detected an error, for instance pipe
  390. // closed. We should exit gracefully.
  391. terminate_session();
  392. }
  393. RELEASE_LOCK(_commands_lock);
  394. }
  395. ////////////////////////////////////////////////////////////////////
  396. // Function: P3DPythonRun::task_check_comm
  397. // Access: Private, Static
  398. // Description: This static function wrapper around check_comm is
  399. // necessary to add the method function to the
  400. // GenericAsyncTask object.
  401. ////////////////////////////////////////////////////////////////////
  402. AsyncTask::DoneStatus P3DPythonRun::
  403. task_check_comm(GenericAsyncTask *task, void *user_data) {
  404. P3DPythonRun *self = (P3DPythonRun *)user_data;
  405. self->check_comm();
  406. return AsyncTask::DS_cont;
  407. }
  408. ////////////////////////////////////////////////////////////////////
  409. // Function: P3DPythonRun::wait_script_response
  410. // Access: Private
  411. // Description: This method is similar to check_comm(), above, but
  412. // instead of handling all events, it waits for a
  413. // specific script_response ID to come back from the
  414. // browser, and leaves all other events in the queue.
  415. ////////////////////////////////////////////////////////////////////
  416. TiXmlDocument *P3DPythonRun::
  417. wait_script_response(int response_id) {
  418. nout << "Waiting script_response " << response_id << "\n";
  419. while (true) {
  420. ACQUIRE_LOCK(_commands_lock);
  421. Commands::iterator ci;
  422. for (ci = _commands.begin(); ci != _commands.end(); ++ci) {
  423. TiXmlDocument *doc = (*ci);
  424. TiXmlElement *xcommand = doc->FirstChildElement("command");
  425. if (xcommand != NULL) {
  426. const char *cmd = xcommand->Attribute("cmd");
  427. if (cmd != NULL && strcmp(cmd, "script_response") == 0) {
  428. int unique_id;
  429. if (xcommand->QueryIntAttribute("unique_id", &unique_id) == TIXML_SUCCESS) {
  430. if (unique_id == response_id) {
  431. // This is the response we were waiting for.
  432. _commands.erase(ci);
  433. RELEASE_LOCK(_commands_lock);
  434. nout << "received script_response: " << *doc << "\n" << flush;
  435. return doc;
  436. }
  437. }
  438. }
  439. // It's not the response we're waiting for, but maybe we need
  440. // to handle it anyway.
  441. bool needs_response = false;
  442. int want_response_id;
  443. if (xcommand->QueryIntAttribute("want_response_id", &want_response_id) == TIXML_SUCCESS) {
  444. // This command will be wanting a response. We'd better
  445. // honor it right away, or we risk deadlock with the browser
  446. // process and the Python process waiting for each other.
  447. _commands.erase(ci);
  448. RELEASE_LOCK(_commands_lock);
  449. handle_command(doc);
  450. delete doc;
  451. ACQUIRE_LOCK(_commands_lock);
  452. break;
  453. }
  454. }
  455. }
  456. if (!_program_continue) {
  457. terminate_session();
  458. }
  459. RELEASE_LOCK(_commands_lock);
  460. // It hasn't shown up yet. Give the sub-thread a chance to
  461. // process the input and append it to the queue.
  462. Thread::force_yield();
  463. }
  464. assert(false);
  465. }
  466. ////////////////////////////////////////////////////////////////////
  467. // Function: P3DPythonRun::py_request_func
  468. // Access: Private
  469. // Description: This method is a special Python function that is
  470. // added as a callback to the AppRunner class, to allow
  471. // Python to upcall into this object.
  472. ////////////////////////////////////////////////////////////////////
  473. PyObject *P3DPythonRun::
  474. py_request_func(PyObject *args) {
  475. int instance_id;
  476. const char *request_type;
  477. PyObject *extra_args;
  478. if (!PyArg_ParseTuple(args, "isO", &instance_id, &request_type, &extra_args)) {
  479. return NULL;
  480. }
  481. if (strcmp(request_type, "wait_script_response") == 0) {
  482. // This is a special case. Instead of generating a new request,
  483. // this means to wait for a particular script_response to come in
  484. // on the wire.
  485. int response_id;
  486. if (!PyArg_ParseTuple(extra_args, "i", &response_id)) {
  487. return NULL;
  488. }
  489. TiXmlDocument *doc = wait_script_response(response_id);
  490. assert(doc != NULL);
  491. TiXmlElement *xcommand = doc->FirstChildElement("command");
  492. assert(xcommand != NULL);
  493. TiXmlElement *xvalue = xcommand->FirstChildElement("value");
  494. PyObject *value = NULL;
  495. if (xvalue != NULL) {
  496. value = xml_to_pyobj(xvalue);
  497. } else {
  498. // An absence of a <value> element is an exception. We will
  499. // return NULL from this function, but first set the error
  500. // condition.
  501. PyErr_SetString(PyExc_EnvironmentError, "Error on script call");
  502. }
  503. delete doc;
  504. return value;
  505. }
  506. TiXmlDocument doc;
  507. TiXmlDeclaration *decl = new TiXmlDeclaration("1.0", "utf-8", "");
  508. TiXmlElement *xrequest = new TiXmlElement("request");
  509. xrequest->SetAttribute("instance_id", instance_id);
  510. xrequest->SetAttribute("rtype", request_type);
  511. doc.LinkEndChild(decl);
  512. doc.LinkEndChild(xrequest);
  513. if (strcmp(request_type, "notify") == 0) {
  514. // A general notification to be sent directly to the instance.
  515. const char *message;
  516. if (!PyArg_ParseTuple(extra_args, "s", &message)) {
  517. return NULL;
  518. }
  519. xrequest->SetAttribute("message", message);
  520. nout << "sent: " << doc << "\n" << flush;
  521. _pipe_write << doc << flush;
  522. } else if (strcmp(request_type, "script") == 0) {
  523. // Meddling with a scripting variable on the browser side.
  524. const char *operation;
  525. PyObject *object;
  526. const char *property_name;
  527. PyObject *value;
  528. int needs_response;
  529. int unique_id;
  530. if (!PyArg_ParseTuple(extra_args, "sOsOii",
  531. &operation, &object, &property_name, &value,
  532. &needs_response, &unique_id)) {
  533. return NULL;
  534. }
  535. xrequest->SetAttribute("operation", operation);
  536. xrequest->SetAttribute("property_name", property_name);
  537. xrequest->SetAttribute("needs_response", (int)(needs_response != 0));
  538. xrequest->SetAttribute("unique_id", unique_id);
  539. TiXmlElement *xobject = pyobj_to_xml(object);
  540. xobject->SetValue("object");
  541. xrequest->LinkEndChild(xobject);
  542. if (strcmp(operation, "call") == 0 && PySequence_Check(value)) {
  543. // A special case: operation "call" receives a tuple of
  544. // parameters; unpack the tuple for the XML.
  545. Py_ssize_t length = PySequence_Length(value);
  546. for (Py_ssize_t i = 0; i < length; ++i) {
  547. PyObject *p = PySequence_GetItem(value, i);
  548. if (p != NULL) {
  549. TiXmlElement *xvalue = pyobj_to_xml(p);
  550. xrequest->LinkEndChild(xvalue);
  551. Py_DECREF(p);
  552. }
  553. }
  554. } else {
  555. // Other kinds of operations receive only a single parameter, if
  556. // any.
  557. TiXmlElement *xvalue = pyobj_to_xml(value);
  558. xrequest->LinkEndChild(xvalue);
  559. }
  560. nout << "sent: " << doc << "\n" << flush;
  561. _pipe_write << doc << flush;
  562. } else {
  563. string message = string("Unsupported request type: ") + string(request_type);
  564. PyErr_SetString(PyExc_ValueError, message.c_str());
  565. return NULL;
  566. }
  567. return Py_BuildValue("");
  568. }
  569. ////////////////////////////////////////////////////////////////////
  570. // Function: P3DPythonRun::st_request_func
  571. // Access: Private, Static
  572. // Description: This is the static wrapper around py_request_func.
  573. ////////////////////////////////////////////////////////////////////
  574. PyObject *P3DPythonRun::
  575. st_request_func(PyObject *, PyObject *args) {
  576. return P3DPythonRun::_global_ptr->py_request_func(args);
  577. }
  578. ////////////////////////////////////////////////////////////////////
  579. // Function: P3DPythonRun::spawn_read_thread
  580. // Access: Private
  581. // Description: Starts the read thread. This thread is responsible
  582. // for reading the standard input socket for XML
  583. // commands and storing them in the _commands queue.
  584. ////////////////////////////////////////////////////////////////////
  585. void P3DPythonRun::
  586. spawn_read_thread() {
  587. assert(!_read_thread_continue);
  588. // We have to use direct OS calls to create the thread instead of
  589. // Panda constructs, because it has to be an actual thread, not
  590. // necessarily a Panda thread (we can't use Panda's simple threads
  591. // implementation, because we can't get overlapped I/O on an
  592. // anonymous pipe in Windows).
  593. _read_thread_continue = true;
  594. SPAWN_THREAD(_read_thread, rt_thread_run, this);
  595. }
  596. ////////////////////////////////////////////////////////////////////
  597. // Function: P3DPythonRun::join_read_thread
  598. // Access: Private
  599. // Description: Waits for the read thread to stop.
  600. ////////////////////////////////////////////////////////////////////
  601. void P3DPythonRun::
  602. join_read_thread() {
  603. _read_thread_continue = false;
  604. _pipe_read.close();
  605. JOIN_THREAD(_read_thread);
  606. }
  607. ////////////////////////////////////////////////////////////////////
  608. // Function: P3DPythonRun::start_instance
  609. // Access: Private
  610. // Description: Starts the indicated instance running within the
  611. // Python process.
  612. ////////////////////////////////////////////////////////////////////
  613. void P3DPythonRun::
  614. start_instance(P3DCInstance *inst, TiXmlElement *xinstance) {
  615. _instances[inst->get_instance_id()] = inst;
  616. TiXmlElement *xfparams = xinstance->FirstChildElement("fparams");
  617. if (xfparams != (TiXmlElement *)NULL) {
  618. set_p3d_filename(inst, xfparams);
  619. }
  620. TiXmlElement *xwparams = xinstance->FirstChildElement("wparams");
  621. if (xwparams != (TiXmlElement *)NULL) {
  622. setup_window(inst, xwparams);
  623. }
  624. }
  625. ////////////////////////////////////////////////////////////////////
  626. // Function: P3DPythonRun::terminate_instance
  627. // Access: Private
  628. // Description: Stops the instance with the indicated id.
  629. ////////////////////////////////////////////////////////////////////
  630. void P3DPythonRun::
  631. terminate_instance(int id) {
  632. Instances::iterator ii = _instances.find(id);
  633. if (ii == _instances.end()) {
  634. nout << "Can't stop instance " << id << ": not started.\n";
  635. return;
  636. }
  637. P3DCInstance *inst = (*ii).second;
  638. _instances.erase(ii);
  639. delete inst;
  640. // TODO: we don't currently have any way to stop just one instance
  641. // of a multi-instance session. This will require a different
  642. // Python interface than ShowBase.
  643. terminate_session();
  644. }
  645. ////////////////////////////////////////////////////////////////////
  646. // Function: P3DPythonRun::set_p3d_filename
  647. // Access: Private
  648. // Description: Sets the startup filename and tokens for the
  649. // indicated instance.
  650. ////////////////////////////////////////////////////////////////////
  651. void P3DPythonRun::
  652. set_p3d_filename(P3DCInstance *inst, TiXmlElement *xfparams) {
  653. string p3d_filename;
  654. const char *p3d_filename_c = xfparams->Attribute("p3d_filename");
  655. if (p3d_filename_c != NULL) {
  656. p3d_filename = p3d_filename_c;
  657. }
  658. PyObject *token_list = PyList_New(0);
  659. TiXmlElement *xtoken = xfparams->FirstChildElement("token");
  660. while (xtoken != NULL) {
  661. string keyword, value;
  662. const char *keyword_c = xtoken->Attribute("keyword");
  663. if (keyword_c != NULL) {
  664. keyword = keyword_c;
  665. }
  666. const char *value_c = xtoken->Attribute("value");
  667. if (value_c != NULL) {
  668. value = value_c;
  669. }
  670. PyObject *tuple = Py_BuildValue("(ss)", keyword.c_str(),
  671. value.c_str());
  672. PyList_Append(token_list, tuple);
  673. Py_DECREF(tuple);
  674. xtoken = xtoken->NextSiblingElement("token");
  675. }
  676. PyObject *result = PyObject_CallMethod
  677. (_runner, (char *)"setP3DFilename", (char *)"sOi", p3d_filename.c_str(),
  678. token_list, inst->get_instance_id());
  679. Py_DECREF(token_list);
  680. if (result == NULL) {
  681. PyErr_Print();
  682. }
  683. Py_XDECREF(result);
  684. }
  685. ////////////////////////////////////////////////////////////////////
  686. // Function: P3DPythonRun::setup_window
  687. // Access: Private
  688. // Description: Sets the window parameters for the indicated instance.
  689. ////////////////////////////////////////////////////////////////////
  690. void P3DPythonRun::
  691. setup_window(int id, TiXmlElement *xwparams) {
  692. Instances::iterator ii = _instances.find(id);
  693. if (ii == _instances.end()) {
  694. nout << "Can't setup window for " << id << ": not started.\n";
  695. return;
  696. }
  697. P3DCInstance *inst = (*ii).second;
  698. setup_window(inst, xwparams);
  699. }
  700. ////////////////////////////////////////////////////////////////////
  701. // Function: P3DPythonRun::setup_window
  702. // Access: Private
  703. // Description: Sets the window parameters for the indicated instance.
  704. ////////////////////////////////////////////////////////////////////
  705. void P3DPythonRun::
  706. setup_window(P3DCInstance *inst, TiXmlElement *xwparams) {
  707. string window_type;
  708. const char *window_type_c = xwparams->Attribute("window_type");
  709. if (window_type_c != NULL) {
  710. window_type = window_type_c;
  711. }
  712. int win_x, win_y, win_width, win_height;
  713. xwparams->Attribute("win_x", &win_x);
  714. xwparams->Attribute("win_y", &win_y);
  715. xwparams->Attribute("win_width", &win_width);
  716. xwparams->Attribute("win_height", &win_height);
  717. long parent_window_handle = 0;
  718. #ifdef _WIN32
  719. int hwnd;
  720. if (xwparams->Attribute("parent_hwnd", &hwnd)) {
  721. parent_window_handle = (long)hwnd;
  722. }
  723. #endif
  724. // TODO: direct this into the particular instance. This will
  725. // require a specialized ShowBase replacement.
  726. PyObject *result = PyObject_CallMethod
  727. (_runner, (char *)"setupWindow", (char *)"siiiii", window_type.c_str(),
  728. win_x, win_y, win_width, win_height,
  729. parent_window_handle);
  730. if (result == NULL) {
  731. PyErr_Print();
  732. }
  733. Py_XDECREF(result);
  734. }
  735. ////////////////////////////////////////////////////////////////////
  736. // Function: P3DPythonRun::terminate_session
  737. // Access: Private
  738. // Description: Stops all currently-running instances.
  739. ////////////////////////////////////////////////////////////////////
  740. void P3DPythonRun::
  741. terminate_session() {
  742. Instances::iterator ii;
  743. for (ii = _instances.begin(); ii != _instances.end(); ++ii) {
  744. P3DCInstance *inst = (*ii).second;
  745. delete inst;
  746. }
  747. _instances.clear();
  748. PyObject *result = PyObject_CallMethod(_taskMgr, (char *)"stop", (char *)"");
  749. if (result == NULL) {
  750. PyErr_Print();
  751. return;
  752. }
  753. Py_DECREF(result);
  754. // The task manager is cleaned up. Let's exit immediately here,
  755. // rather than returning all the way up. This just makes it easier
  756. // when we call terminate_session() from a deeply-nested loop.
  757. exit(0);
  758. }
  759. ////////////////////////////////////////////////////////////////////
  760. // Function: P3DPythonRun::pyobj_to_xml
  761. // Access: Private
  762. // Description: Converts the indicated PyObject to the appropriate
  763. // XML representation of a P3D_value type, and returns a
  764. // freshly-allocated TiXmlElement.
  765. ////////////////////////////////////////////////////////////////////
  766. TiXmlElement *P3DPythonRun::
  767. pyobj_to_xml(PyObject *value) {
  768. TiXmlElement *xvalue = new TiXmlElement("value");
  769. if (value == Py_None) {
  770. // None.
  771. xvalue->SetAttribute("type", "none");
  772. } else if (PyBool_Check(value)) {
  773. // A bool value.
  774. xvalue->SetAttribute("type", "bool");
  775. xvalue->SetAttribute("value", PyObject_IsTrue(value));
  776. } else if (PyInt_Check(value)) {
  777. // A plain integer value.
  778. xvalue->SetAttribute("type", "int");
  779. xvalue->SetAttribute("value", PyInt_AsLong(value));
  780. } else if (PyLong_Check(value)) {
  781. // A long integer value. This gets converted either as an integer
  782. // or as a floating-point type, whichever fits.
  783. long lvalue = PyLong_AsLong(value);
  784. if (PyErr_Occurred()) {
  785. // It won't fit as an integer; make it a double.
  786. PyErr_Clear();
  787. xvalue->SetAttribute("type", "float");
  788. xvalue->SetDoubleAttribute("value", PyLong_AsDouble(value));
  789. } else {
  790. // It fits as an integer.
  791. xvalue->SetAttribute("type", "int");
  792. xvalue->SetAttribute("value", lvalue);
  793. }
  794. } else if (PyFloat_Check(value)) {
  795. // A floating-point value.
  796. xvalue->SetAttribute("type", "float");
  797. xvalue->SetDoubleAttribute("value", PyFloat_AsDouble(value));
  798. } else if (PyUnicode_Check(value)) {
  799. // A unicode value. Convert to utf-8 for the XML encoding.
  800. xvalue->SetAttribute("type", "string");
  801. PyObject *as_str = PyUnicode_AsUTF8String(value);
  802. if (as_str != NULL) {
  803. char *buffer;
  804. Py_ssize_t length;
  805. if (PyString_AsStringAndSize(as_str, &buffer, &length) != -1) {
  806. string str(buffer, length);
  807. xvalue->SetAttribute("value", str);
  808. }
  809. Py_DECREF(as_str);
  810. }
  811. } else if (PyString_Check(value)) {
  812. // A string value.
  813. xvalue->SetAttribute("type", "string");
  814. char *buffer;
  815. Py_ssize_t length;
  816. if (PyString_AsStringAndSize(value, &buffer, &length) != -1) {
  817. string str(buffer, length);
  818. xvalue->SetAttribute("value", str);
  819. }
  820. } else if (PyObject_IsInstance(value, _undefined_object_class)) {
  821. // This is an UndefinedObject.
  822. xvalue->SetAttribute("type", "undefined");
  823. } else if (PyObject_IsInstance(value, _browser_object_class)) {
  824. // This is a BrowserObject, a reference to an object that actually
  825. // exists in the host namespace. So, pass up the appropriate
  826. // object ID.
  827. PyObject *objectId = PyObject_GetAttrString(value, (char *)"_BrowserObject__objectId");
  828. if (objectId != NULL) {
  829. int object_id = PyInt_AsLong(objectId);
  830. xvalue->SetAttribute("type", "browser");
  831. xvalue->SetAttribute("object_id", object_id);
  832. Py_DECREF(objectId);
  833. }
  834. } else {
  835. // Some other kind of object. Make it a generic Python object.
  836. // This is more expensive for the caller to deal with--it requires
  837. // a back-and-forth across the XML pipe--but it's much more
  838. // general.
  839. // TODO: pass pointers better.
  840. xvalue->SetAttribute("type", "python");
  841. xvalue->SetAttribute("object_id", (int)(intptr_t)value);
  842. // TODO: fix this hack, properly manage these reference counts.
  843. Py_INCREF(value);
  844. }
  845. return xvalue;
  846. }
  847. ////////////////////////////////////////////////////////////////////
  848. // Function: P3DPythonRun::xml_to_pyobj
  849. // Access: Private
  850. // Description: Converts the XML representation of a P3D_value type
  851. // into the equivalent Python object and returns it.
  852. ////////////////////////////////////////////////////////////////////
  853. PyObject *P3DPythonRun::
  854. xml_to_pyobj(TiXmlElement *xvalue) {
  855. const char *type = xvalue->Attribute("type");
  856. if (strcmp(type, "none") == 0) {
  857. return Py_BuildValue("");
  858. } else if (strcmp(type, "bool") == 0) {
  859. int value;
  860. if (xvalue->QueryIntAttribute("value", &value) == TIXML_SUCCESS) {
  861. return PyBool_FromLong(value);
  862. }
  863. } else if (strcmp(type, "int") == 0) {
  864. int value;
  865. if (xvalue->QueryIntAttribute("value", &value) == TIXML_SUCCESS) {
  866. return PyInt_FromLong(value);
  867. }
  868. } else if (strcmp(type, "float") == 0) {
  869. double value;
  870. if (xvalue->QueryDoubleAttribute("value", &value) == TIXML_SUCCESS) {
  871. return PyFloat_FromDouble(value);
  872. }
  873. } else if (strcmp(type, "string") == 0) {
  874. // Using the string form here instead of the char * form, so we
  875. // don't get tripped up on embedded null characters.
  876. const string *value = xvalue->Attribute(string("value"));
  877. if (value != NULL) {
  878. return PyString_FromStringAndSize(value->data(), value->length());
  879. }
  880. } else if (strcmp(type, "undefined") == 0) {
  881. Py_INCREF(_undefined);
  882. return _undefined;
  883. } else if (strcmp(type, "browser") == 0) {
  884. int object_id;
  885. if (xvalue->QueryIntAttribute("object_id", &object_id) == TIXML_SUCCESS) {
  886. // Construct a new BrowserObject wrapper around this object.
  887. return PyObject_CallFunction(_browser_object_class, (char *)"Oi",
  888. _runner, object_id);
  889. }
  890. } else if (strcmp(type, "python") == 0) {
  891. int object_id;
  892. if (xvalue->QueryIntAttribute("object_id", &object_id) == TIXML_SUCCESS) {
  893. return (PyObject *)(void *)object_id;
  894. }
  895. }
  896. // Something went wrong in decoding.
  897. return Py_BuildValue("");
  898. }
  899. ////////////////////////////////////////////////////////////////////
  900. // Function: P3DPythonRun::rt_thread_run
  901. // Access: Private
  902. // Description: The main function for the read thread.
  903. ////////////////////////////////////////////////////////////////////
  904. void P3DPythonRun::
  905. rt_thread_run() {
  906. while (_read_thread_continue) {
  907. TiXmlDocument *doc = new TiXmlDocument;
  908. _pipe_read >> *doc;
  909. if (!_pipe_read || _pipe_read.eof()) {
  910. // Some error on reading. Abort.
  911. _program_continue = false;
  912. return;
  913. }
  914. // Successfully read an XML document.
  915. // Check for one special case: the "exit" command means we shut
  916. // down the read thread along with everything else.
  917. TiXmlElement *xcommand = doc->FirstChildElement("command");
  918. if (xcommand != NULL) {
  919. const char *cmd = xcommand->Attribute("cmd");
  920. if (cmd != NULL) {
  921. if (strcmp(cmd, "exit") == 0) {
  922. _read_thread_continue = false;
  923. }
  924. }
  925. }
  926. // Feed the command up to the parent.
  927. ACQUIRE_LOCK(_commands_lock);
  928. _commands.push_back(doc);
  929. RELEASE_LOCK(_commands_lock);
  930. }
  931. }
  932. ////////////////////////////////////////////////////////////////////
  933. // Function: main
  934. // Description: Starts the program running.
  935. ////////////////////////////////////////////////////////////////////
  936. int
  937. main(int argc, char *argv[]) {
  938. P3DPythonRun::_global_ptr = new P3DPythonRun(argc, argv);
  939. if (!P3DPythonRun::_global_ptr->run_python()) {
  940. nout << "Couldn't initialize Python.\n";
  941. return 1;
  942. }
  943. return 0;
  944. }