p3dPythonRun.cxx 58 KB

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