p3dPythonRun.cxx 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858
  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::set_window_open
  334. // Access: Public
  335. // Description: Called from low-level Panda (via the P3DWindowHandle
  336. // object) when a child window has been attached or
  337. // detached from the browser window. This triggers the
  338. // "onwindowattach" and "onwindowdetach" JavaScript
  339. // notifications.
  340. ////////////////////////////////////////////////////////////////////
  341. void P3DPythonRun::
  342. set_window_open(P3DCInstance *inst, bool is_open) {
  343. TiXmlDocument doc;
  344. TiXmlElement *xrequest = new TiXmlElement("request");
  345. xrequest->SetAttribute("instance_id", inst->get_instance_id());
  346. xrequest->SetAttribute("rtype", "notify");
  347. if (is_open) {
  348. xrequest->SetAttribute("message", "onwindowattach");
  349. } else {
  350. xrequest->SetAttribute("message", "onwindowdetach");
  351. }
  352. doc.LinkEndChild(xrequest);
  353. write_xml(_pipe_write, &doc, nout);
  354. }
  355. ////////////////////////////////////////////////////////////////////
  356. // Function: P3DPythonRun::request_keyboard_focus
  357. // Access: Public
  358. // Description: Called from low-level Panda (via the P3DWindowHandle
  359. // object) when its main window requires keyboard focus,
  360. // but is unable to assign it directly. This is
  361. // particularly necessary under Windows Vista, where a
  362. // child window of the browser is specifically
  363. // disallowed from being given keyboard focus.
  364. //
  365. // This sends a notify request up to the parent process,
  366. // to ask the parent to manage keyboard events by proxy,
  367. // and send them back down to Panda, again via the
  368. // P3DWindowHandle.
  369. ////////////////////////////////////////////////////////////////////
  370. void P3DPythonRun::
  371. request_keyboard_focus(P3DCInstance *inst) {
  372. TiXmlDocument doc;
  373. TiXmlElement *xrequest = new TiXmlElement("request");
  374. xrequest->SetAttribute("instance_id", inst->get_instance_id());
  375. xrequest->SetAttribute("rtype", "notify");
  376. xrequest->SetAttribute("message", "keyboardfocus");
  377. doc.LinkEndChild(xrequest);
  378. write_xml(_pipe_write, &doc, nout);
  379. }
  380. ////////////////////////////////////////////////////////////////////
  381. // Function: P3DPythonRun::run_interactive_console
  382. // Access: Private
  383. // Description: Gives the user a chance to type interactive Python
  384. // commands, for easy development of a p3d application.
  385. // This method is only called if "interactive_console=1"
  386. // is set as a web token, and "allow_python_dev" is set
  387. // within the application itself.
  388. ////////////////////////////////////////////////////////////////////
  389. void P3DPythonRun::
  390. run_interactive_console() {
  391. #ifdef _WIN32
  392. // Make sure that control-C support is enabled for the interpreter.
  393. SetConsoleCtrlHandler(NULL, false);
  394. #endif
  395. // The "readline" module makes the Python prompt friendlier, with
  396. // command history and everything. Simply importing it is
  397. // sufficient.
  398. PyObject *readline_module = PyImport_ImportModule("readline");
  399. if (readline_module == NULL) {
  400. // But, the module might not exist on certain platforms. If not,
  401. // no sweat.
  402. PyErr_Clear();
  403. } else {
  404. Py_DECREF(readline_module);
  405. }
  406. PyRun_InteractiveLoop(stdin, "<stdin>");
  407. }
  408. ////////////////////////////////////////////////////////////////////
  409. // Function: P3DPythonRun::handle_command
  410. // Access: Private
  411. // Description: Handles a command received from the plugin host, via
  412. // an XML syntax on the wire. Ownership of the XML
  413. // document object is passed into this method.
  414. //
  415. // It's important *not* to be holding _commands_lock
  416. // when calling this method.
  417. ////////////////////////////////////////////////////////////////////
  418. void P3DPythonRun::
  419. handle_command(TiXmlDocument *doc) {
  420. TiXmlElement *xcommand = doc->FirstChildElement("command");
  421. if (xcommand != NULL) {
  422. bool needs_response = false;
  423. int want_response_id;
  424. if (xcommand->QueryIntAttribute("want_response_id", &want_response_id) == TIXML_SUCCESS) {
  425. // This command will be waiting for a response.
  426. needs_response = true;
  427. }
  428. const char *cmd = xcommand->Attribute("cmd");
  429. if (cmd != NULL) {
  430. if (strcmp(cmd, "init") == 0) {
  431. assert(!needs_response);
  432. // The only purpose of the "init" command is to send us a
  433. // unique session ID, which in fact we don't do much with.
  434. xcommand->Attribute("session_id", &_session_id);
  435. // We do use it to initiate our object id sequence with a
  436. // number at least a little bit distinct from other sessions,
  437. // though. No technical requirement that we do this, but it
  438. // does make debugging the logs a bit easier.
  439. _next_sent_id = _session_id * 1000;
  440. PyObject *obj = PyObject_CallMethod(_runner, (char*)"setSessionId", (char *)"i", _session_id);
  441. Py_XDECREF(obj);
  442. } else if (strcmp(cmd, "start_instance") == 0) {
  443. assert(!needs_response);
  444. TiXmlElement *xinstance = xcommand->FirstChildElement("instance");
  445. if (xinstance != (TiXmlElement *)NULL) {
  446. P3DCInstance *inst = new P3DCInstance(xinstance);
  447. start_instance(inst, xinstance);
  448. }
  449. } else if (strcmp(cmd, "terminate_instance") == 0) {
  450. assert(!needs_response);
  451. int instance_id;
  452. if (xcommand->QueryIntAttribute("instance_id", &instance_id) == TIXML_SUCCESS) {
  453. terminate_instance(instance_id);
  454. }
  455. } else if (strcmp(cmd, "setup_window") == 0) {
  456. assert(!needs_response);
  457. int instance_id;
  458. TiXmlElement *xwparams = xcommand->FirstChildElement("wparams");
  459. if (xwparams != (TiXmlElement *)NULL &&
  460. xcommand->QueryIntAttribute("instance_id", &instance_id) == TIXML_SUCCESS) {
  461. setup_window(instance_id, xwparams);
  462. }
  463. } else if (strcmp(cmd, "windows_message") == 0) {
  464. assert(!needs_response);
  465. // This is a special message that we use to proxy keyboard
  466. // events from the parent process down into Panda, a necessary
  467. // hack on Vista.
  468. int instance_id = 0, msg = 0, wparam = 0, lparam = 0;
  469. xcommand->Attribute("instance_id", &instance_id);
  470. xcommand->Attribute("msg", &msg);
  471. xcommand->Attribute("wparam", &wparam);
  472. xcommand->Attribute("lparam", &lparam);
  473. send_windows_message(instance_id, msg, wparam, lparam);
  474. } else if (strcmp(cmd, "exit") == 0) {
  475. assert(!needs_response);
  476. terminate_session();
  477. } else if (strcmp(cmd, "pyobj") == 0) {
  478. // Manipulate or query a python object.
  479. handle_pyobj_command(xcommand, needs_response, want_response_id);
  480. } else if (strcmp(cmd, "script_response") == 0) {
  481. // Response from a script request. In this case, we just
  482. // store it away instead of processing it immediately.
  483. MutexHolder holder(_responses_lock);
  484. _responses.push_back(doc);
  485. // And now we must return out, instead of deleting the
  486. // document at the bottom of this method.
  487. return;
  488. } else if (strcmp(cmd, "drop_pyobj") == 0) {
  489. int object_id;
  490. if (xcommand->QueryIntAttribute("object_id", &object_id) == TIXML_SUCCESS) {
  491. SentObjects::iterator si = _sent_objects.find(object_id);
  492. if (si != _sent_objects.end()) {
  493. PyObject *obj = (*si).second;
  494. Py_DECREF(obj);
  495. _sent_objects.erase(si);
  496. }
  497. }
  498. } else {
  499. nout << "Unhandled command " << cmd << "\n";
  500. if (needs_response) {
  501. // Better send a response.
  502. TiXmlDocument doc;
  503. TiXmlElement *xresponse = new TiXmlElement("response");
  504. xresponse->SetAttribute("response_id", want_response_id);
  505. doc.LinkEndChild(xresponse);
  506. write_xml(_pipe_write, &doc, nout);
  507. }
  508. }
  509. }
  510. }
  511. delete doc;
  512. }
  513. ////////////////////////////////////////////////////////////////////
  514. // Function: P3DPythonRun::handle_pyobj_command
  515. // Access: Private
  516. // Description: Handles the pyobj command, which queries or modifies
  517. // a Python object from the browser scripts.
  518. ////////////////////////////////////////////////////////////////////
  519. void P3DPythonRun::
  520. handle_pyobj_command(TiXmlElement *xcommand, bool needs_response,
  521. int want_response_id) {
  522. TiXmlDocument doc;
  523. TiXmlElement *xresponse = new TiXmlElement("response");
  524. xresponse->SetAttribute("response_id", want_response_id);
  525. doc.LinkEndChild(xresponse);
  526. const char *op = xcommand->Attribute("op");
  527. if (op != NULL && !PyErr_Occurred()) {
  528. if (strcmp(op, "get_panda_script_object") == 0) {
  529. // Get Panda's toplevel Python object.
  530. PyObject *obj = PyObject_CallMethod(_runner, (char*)"getPandaScriptObject", (char *)"");
  531. if (obj != NULL) {
  532. xresponse->LinkEndChild(pyobj_to_xml(obj));
  533. Py_DECREF(obj);
  534. }
  535. } else if (strcmp(op, "set_browser_script_object") == 0) {
  536. // Set the Browser's toplevel window object.
  537. PyObject *obj;
  538. TiXmlElement *xvalue = xcommand->FirstChildElement("value");
  539. if (xvalue != NULL) {
  540. obj = xml_to_pyobj(xvalue);
  541. } else {
  542. obj = Py_None;
  543. Py_INCREF(obj);
  544. }
  545. PyObject *result = PyObject_CallMethod
  546. (_runner, (char *)"setBrowserScriptObject", (char *)"O", obj);
  547. Py_DECREF(obj);
  548. Py_XDECREF(result);
  549. } else if (strcmp(op, "call") == 0) {
  550. // Call the named method on the indicated object, or the object
  551. // itself if method_name isn't given.
  552. TiXmlElement *xobject = xcommand->FirstChildElement("object");
  553. if (xobject != NULL) {
  554. PyObject *obj = xml_to_pyobj(xobject);
  555. const char *method_name = xcommand->Attribute("method_name");
  556. // Build up a list of params.
  557. PyObject *list = PyList_New(0);
  558. TiXmlElement *xchild = xcommand->FirstChildElement("value");
  559. while (xchild != NULL) {
  560. PyObject *child = xml_to_pyobj(xchild);
  561. PyList_Append(list, child);
  562. Py_DECREF(child);
  563. xchild = xchild->NextSiblingElement("value");
  564. }
  565. // Convert the list to a tuple for the call.
  566. PyObject *params = PyList_AsTuple(list);
  567. Py_DECREF(list);
  568. // Now call the method.
  569. PyObject *result = NULL;
  570. if (method_name == NULL) {
  571. // No method name; call the object directly.
  572. result = PyObject_CallObject(obj, params);
  573. // Several special-case "method" names.
  574. } else if (strcmp(method_name, "__bool__") == 0) {
  575. result = PyBool_FromLong(PyObject_IsTrue(obj));
  576. } else if (strcmp(method_name, "__int__") == 0) {
  577. result = PyNumber_Int(obj);
  578. } else if (strcmp(method_name, "__float__") == 0) {
  579. result = PyNumber_Float(obj);
  580. } else if (strcmp(method_name, "__repr__") == 0) {
  581. result = PyObject_Repr(obj);
  582. } else if (strcmp(method_name, "__str__") == 0 ||
  583. strcmp(method_name, "toString") == 0) {
  584. result = PyObject_Str(obj);
  585. } else if (strcmp(method_name, "__set_property__") == 0) {
  586. // We call these methods __set_property__ et al instead of
  587. // __setattr__ et al, because they do not precisely
  588. // duplicate the Python semantics.
  589. char *property_name;
  590. PyObject *value;
  591. if (PyArg_ParseTuple(params, "sO", &property_name, &value)) {
  592. bool success = false;
  593. // If it already exists as an attribute, update it there.
  594. if (PyObject_HasAttrString(obj, property_name)) {
  595. if (PyObject_SetAttrString(obj, property_name, value) != -1) {
  596. success = true;
  597. } else {
  598. PyErr_Clear();
  599. }
  600. }
  601. // If the object supports the mapping protocol, store it
  602. // in the object's dictionary.
  603. if (!success && PyMapping_Check(obj)) {
  604. if (PyMapping_SetItemString(obj, property_name, value) != -1) {
  605. success = true;
  606. } else {
  607. PyErr_Clear();
  608. }
  609. }
  610. // Finally, try to store it on the object.
  611. if (!success) {
  612. if (PyObject_SetAttrString(obj, property_name, value) != -1) {
  613. success = true;
  614. } else {
  615. PyErr_Clear();
  616. }
  617. }
  618. if (success) {
  619. result = Py_True;
  620. } else {
  621. result = Py_False;
  622. }
  623. Py_INCREF(result);
  624. }
  625. } else if (strcmp(method_name, "__del_property__") == 0) {
  626. char *property_name;
  627. if (PyArg_ParseTuple(params, "s", &property_name)) {
  628. bool success = false;
  629. if (PyObject_HasAttrString(obj, property_name)) {
  630. if (PyObject_DelAttrString(obj, property_name) != -1) {
  631. success = true;
  632. } else {
  633. PyErr_Clear();
  634. }
  635. }
  636. if (!success) {
  637. if (PyObject_DelItemString(obj, property_name) != -1) {
  638. success = true;
  639. } else {
  640. PyErr_Clear();
  641. }
  642. }
  643. if (success) {
  644. result = Py_True;
  645. } else {
  646. result = Py_False;
  647. }
  648. Py_INCREF(result);
  649. }
  650. } else if (strcmp(method_name, "__get_property__") == 0) {
  651. char *property_name;
  652. if (PyArg_ParseTuple(params, "s", &property_name)) {
  653. bool success = false;
  654. if (PyObject_HasAttrString(obj, property_name)) {
  655. result = PyObject_GetAttrString(obj, property_name);
  656. if (result != NULL) {
  657. success = true;
  658. } else {
  659. PyErr_Clear();
  660. }
  661. }
  662. if (!success) {
  663. if (PyMapping_HasKeyString(obj, property_name)) {
  664. result = PyMapping_GetItemString(obj, property_name);
  665. if (result != NULL) {
  666. success = true;
  667. } else {
  668. PyErr_Clear();
  669. }
  670. }
  671. }
  672. if (!success) {
  673. result = NULL;
  674. }
  675. }
  676. } else if (strcmp(method_name, "__has_method__") == 0) {
  677. char *property_name;
  678. result = Py_False;
  679. if (PyArg_ParseTuple(params, "s", &property_name)) {
  680. if (*property_name) {
  681. // Check for a callable method
  682. if (PyObject_HasAttrString(obj, property_name)) {
  683. PyObject *prop = PyObject_GetAttrString(obj, property_name);
  684. if (PyCallable_Check(prop)) {
  685. result = Py_True;
  686. }
  687. Py_DECREF(prop);
  688. }
  689. } else {
  690. // Check for the default method
  691. if (PyCallable_Check(obj)) {
  692. result = Py_True;
  693. }
  694. }
  695. }
  696. Py_INCREF(result);
  697. } else {
  698. // Not a special-case name. Call the named method.
  699. PyObject *method = PyObject_GetAttrString(obj, (char *)method_name);
  700. if (method != NULL) {
  701. result = PyObject_CallObject(method, params);
  702. Py_DECREF(method);
  703. }
  704. }
  705. Py_DECREF(params);
  706. // Feed the return value back through the XML pipe to the
  707. // caller.
  708. if (result != NULL) {
  709. xresponse->LinkEndChild(pyobj_to_xml(result));
  710. Py_DECREF(result);
  711. } else {
  712. // Print the Python error message if there was one.
  713. PyErr_Print();
  714. }
  715. Py_DECREF(obj);
  716. }
  717. }
  718. }
  719. if (needs_response) {
  720. write_xml(_pipe_write, &doc, nout);
  721. }
  722. }
  723. ////////////////////////////////////////////////////////////////////
  724. // Function: P3DPythonRun::check_comm
  725. // Access: Private
  726. // Description: This method is added to the task manager (via
  727. // st_check_comm, below) so that it gets a call every
  728. // frame. Its job is to check for commands received
  729. // from the plugin host in the parent process.
  730. ////////////////////////////////////////////////////////////////////
  731. void P3DPythonRun::
  732. check_comm() {
  733. // nout << ":";
  734. ACQUIRE_LOCK(_commands_lock);
  735. while (!_commands.empty()) {
  736. TiXmlDocument *doc = _commands.front();
  737. _commands.pop_front();
  738. RELEASE_LOCK(_commands_lock);
  739. handle_command(doc);
  740. if (_session_terminated) {
  741. return;
  742. }
  743. ACQUIRE_LOCK(_commands_lock);
  744. }
  745. RELEASE_LOCK(_commands_lock);
  746. if (!_program_continue) {
  747. // The low-level thread detected an error, for instance pipe
  748. // closed. We should exit gracefully.
  749. terminate_session();
  750. return;
  751. }
  752. // Sleep to yield the timeslice, but only if we're not running in
  753. // the main thread.
  754. if (Thread::get_current_thread() != Thread::get_main_thread()) {
  755. Thread::sleep(0.001);
  756. }
  757. }
  758. ////////////////////////////////////////////////////////////////////
  759. // Function: P3DPythonRun::st_check_comm
  760. // Access: Private, Static
  761. // Description: This is a static Python wrapper around py_check_comm,
  762. // needed to add the function to a PythonTask.
  763. ////////////////////////////////////////////////////////////////////
  764. PyObject *P3DPythonRun::
  765. st_check_comm(PyObject *, PyObject *args) {
  766. P3DPythonRun::_global_ptr->check_comm();
  767. return Py_BuildValue("i", AsyncTask::DS_cont);
  768. }
  769. ////////////////////////////////////////////////////////////////////
  770. // Function: P3DPythonRun::wait_script_response
  771. // Access: Private
  772. // Description: This method is similar to check_comm(), above, but
  773. // instead of handling all events, it waits for a
  774. // specific script_response ID to come back from the
  775. // browser, and leaves all other events in the queue.
  776. ////////////////////////////////////////////////////////////////////
  777. TiXmlDocument *P3DPythonRun::
  778. wait_script_response(int response_id) {
  779. // nout << "waiting script_response " << response_id << "\n";
  780. while (true) {
  781. Commands::iterator ci;
  782. // First, walk through the _commands queue to see if there's
  783. // anything that needs immediate processing.
  784. ACQUIRE_LOCK(_commands_lock);
  785. for (ci = _commands.begin(); ci != _commands.end(); ++ci) {
  786. TiXmlDocument *doc = (*ci);
  787. TiXmlElement *xcommand = doc->FirstChildElement("command");
  788. if (xcommand != NULL) {
  789. const char *cmd = xcommand->Attribute("cmd");
  790. if ((cmd != NULL && strcmp(cmd, "script_response") == 0) ||
  791. xcommand->Attribute("want_response_id") != NULL) {
  792. // This is either a response, or it's a command that will
  793. // want a response itself. In either case we should handle
  794. // it right away. ("handling" a response means moving it to
  795. // the _responses queue.)
  796. _commands.erase(ci);
  797. RELEASE_LOCK(_commands_lock);
  798. handle_command(doc);
  799. if (_session_terminated) {
  800. return NULL;
  801. }
  802. ACQUIRE_LOCK(_commands_lock);
  803. break;
  804. }
  805. }
  806. }
  807. RELEASE_LOCK(_commands_lock);
  808. // Now, walk through the _responses queue to look for the
  809. // particular response we're waiting for.
  810. _responses_lock.acquire();
  811. for (ci = _responses.begin(); ci != _responses.end(); ++ci) {
  812. TiXmlDocument *doc = (*ci);
  813. TiXmlElement *xcommand = doc->FirstChildElement("command");
  814. assert(xcommand != NULL);
  815. const char *cmd = xcommand->Attribute("cmd");
  816. assert(cmd != NULL && strcmp(cmd, "script_response") == 0);
  817. int unique_id;
  818. if (xcommand->QueryIntAttribute("unique_id", &unique_id) == TIXML_SUCCESS) {
  819. if (unique_id == response_id) {
  820. // This is the response we were waiting for.
  821. _responses.erase(ci);
  822. _responses_lock.release();
  823. // nout << "got script_response " << unique_id << "\n";
  824. return doc;
  825. }
  826. }
  827. }
  828. _responses_lock.release();
  829. if (!_program_continue) {
  830. terminate_session();
  831. return NULL;
  832. }
  833. #ifdef _WIN32
  834. // Make sure we process the Windows event loop while we're
  835. // waiting, or everything that depends on Windows messages will
  836. // starve.
  837. // We appear to be best off with just a single PeekMessage() call
  838. // here; the full message pump seems to cause problems.
  839. MSG msg;
  840. PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE | PM_NOYIELD);
  841. #endif // _WIN32
  842. // nout << ".";
  843. // It hasn't shown up yet. Give the sub-thread a chance to
  844. // process the input and append it to the queue.
  845. Thread::force_yield();
  846. }
  847. assert(false);
  848. }
  849. ////////////////////////////////////////////////////////////////////
  850. // Function: P3DPythonRun::py_request_func
  851. // Access: Private
  852. // Description: This method is a special Python function that is
  853. // added as a callback to the AppRunner class, to allow
  854. // Python to upcall into this object.
  855. ////////////////////////////////////////////////////////////////////
  856. PyObject *P3DPythonRun::
  857. py_request_func(PyObject *args) {
  858. int instance_id;
  859. const char *request_type;
  860. PyObject *extra_args;
  861. if (!PyArg_ParseTuple(args, "isO", &instance_id, &request_type, &extra_args)) {
  862. return NULL;
  863. }
  864. if (strcmp(request_type, "wait_script_response") == 0) {
  865. // This is a special case. Instead of generating a new request,
  866. // this means to wait for a particular script_response to come in
  867. // on the wire.
  868. int response_id;
  869. if (!PyArg_ParseTuple(extra_args, "i", &response_id)) {
  870. return NULL;
  871. }
  872. TiXmlDocument *doc = wait_script_response(response_id);
  873. if (_session_terminated) {
  874. return Py_BuildValue("");
  875. }
  876. assert(doc != NULL);
  877. TiXmlElement *xcommand = doc->FirstChildElement("command");
  878. assert(xcommand != NULL);
  879. TiXmlElement *xvalue = xcommand->FirstChildElement("value");
  880. PyObject *value = NULL;
  881. if (xvalue != NULL) {
  882. value = xml_to_pyobj(xvalue);
  883. } else {
  884. // An absence of a <value> element is an exception. We will
  885. // return NULL from this function, but first set the error
  886. // condition.
  887. PyErr_SetString(PyExc_EnvironmentError, "Error on script call");
  888. }
  889. delete doc;
  890. return value;
  891. }
  892. TiXmlDocument doc;
  893. TiXmlElement *xrequest = new TiXmlElement("request");
  894. xrequest->SetAttribute("instance_id", instance_id);
  895. xrequest->SetAttribute("rtype", request_type);
  896. doc.LinkEndChild(xrequest);
  897. if (strcmp(request_type, "notify") == 0) {
  898. // A general notification to be sent directly to the instance.
  899. const char *message;
  900. if (!PyArg_ParseTuple(extra_args, "s", &message)) {
  901. return NULL;
  902. }
  903. xrequest->SetAttribute("message", message);
  904. write_xml(_pipe_write, &doc, nout);
  905. } else if (strcmp(request_type, "script") == 0) {
  906. // Meddling with a scripting variable on the browser side.
  907. const char *operation;
  908. PyObject *object;
  909. const char *property_name;
  910. PyObject *value;
  911. int needs_response;
  912. int unique_id;
  913. if (!PyArg_ParseTuple(extra_args, "sOsOii",
  914. &operation, &object, &property_name, &value,
  915. &needs_response, &unique_id)) {
  916. return NULL;
  917. }
  918. xrequest->SetAttribute("operation", operation);
  919. xrequest->SetAttribute("property_name", property_name);
  920. xrequest->SetAttribute("needs_response", (int)(needs_response != 0));
  921. xrequest->SetAttribute("unique_id", unique_id);
  922. TiXmlElement *xobject = pyobj_to_xml(object);
  923. xobject->SetValue("object");
  924. xrequest->LinkEndChild(xobject);
  925. TiXmlElement *xvalue = pyobj_to_xml(value);
  926. xrequest->LinkEndChild(xvalue);
  927. write_xml(_pipe_write, &doc, nout);
  928. } else if (strcmp(request_type, "drop_p3dobj") == 0) {
  929. // Release a particular P3D_object that we were holding a
  930. // reference to.
  931. int object_id;
  932. if (!PyArg_ParseTuple(extra_args, "i", &object_id)) {
  933. return NULL;
  934. }
  935. xrequest->SetAttribute("object_id", object_id);
  936. write_xml(_pipe_write, &doc, nout);
  937. } else {
  938. string message = string("Unsupported request type: ") + string(request_type);
  939. PyErr_SetString(PyExc_ValueError, message.c_str());
  940. return NULL;
  941. }
  942. return Py_BuildValue("");
  943. }
  944. ////////////////////////////////////////////////////////////////////
  945. // Function: P3DPythonRun::st_request_func
  946. // Access: Private, Static
  947. // Description: This is the static wrapper around py_request_func.
  948. ////////////////////////////////////////////////////////////////////
  949. PyObject *P3DPythonRun::
  950. st_request_func(PyObject *, PyObject *args) {
  951. return P3DPythonRun::_global_ptr->py_request_func(args);
  952. }
  953. ////////////////////////////////////////////////////////////////////
  954. // Function: P3DPythonRun::spawn_read_thread
  955. // Access: Private
  956. // Description: Starts the read thread. This thread is responsible
  957. // for reading the standard input socket for XML
  958. // commands and storing them in the _commands queue.
  959. ////////////////////////////////////////////////////////////////////
  960. void P3DPythonRun::
  961. spawn_read_thread() {
  962. assert(!_read_thread_continue);
  963. // We have to use direct OS calls to create the thread instead of
  964. // Panda constructs, because it has to be an actual thread, not
  965. // necessarily a Panda thread (we can't use Panda's simple threads
  966. // implementation, because we can't get overlapped I/O on an
  967. // anonymous pipe in Windows).
  968. _read_thread_continue = true;
  969. SPAWN_THREAD(_read_thread, rt_thread_run, this);
  970. }
  971. ////////////////////////////////////////////////////////////////////
  972. // Function: P3DPythonRun::join_read_thread
  973. // Access: Private
  974. // Description: Waits for the read thread to stop.
  975. ////////////////////////////////////////////////////////////////////
  976. void P3DPythonRun::
  977. join_read_thread() {
  978. _read_thread_continue = false;
  979. JOIN_THREAD(_read_thread);
  980. }
  981. ////////////////////////////////////////////////////////////////////
  982. // Function: P3DPythonRun::start_instance
  983. // Access: Private
  984. // Description: Starts the indicated instance running within the
  985. // Python process.
  986. ////////////////////////////////////////////////////////////////////
  987. void P3DPythonRun::
  988. start_instance(P3DCInstance *inst, TiXmlElement *xinstance) {
  989. _instances[inst->get_instance_id()] = inst;
  990. set_instance_info(inst, xinstance);
  991. TiXmlElement *xpackage = xinstance->FirstChildElement("package");
  992. while (xpackage != (TiXmlElement *)NULL) {
  993. add_package_info(inst, xpackage);
  994. xpackage = xpackage->NextSiblingElement("package");
  995. }
  996. TiXmlElement *xfparams = xinstance->FirstChildElement("fparams");
  997. if (xfparams != (TiXmlElement *)NULL) {
  998. set_p3d_filename(inst, xfparams);
  999. }
  1000. TiXmlElement *xwparams = xinstance->FirstChildElement("wparams");
  1001. if (xwparams != (TiXmlElement *)NULL) {
  1002. setup_window(inst, xwparams);
  1003. }
  1004. }
  1005. ////////////////////////////////////////////////////////////////////
  1006. // Function: P3DPythonRun::terminate_instance
  1007. // Access: Private
  1008. // Description: Stops the instance with the indicated id.
  1009. ////////////////////////////////////////////////////////////////////
  1010. void P3DPythonRun::
  1011. terminate_instance(int id) {
  1012. Instances::iterator ii = _instances.find(id);
  1013. if (ii == _instances.end()) {
  1014. nout << "Can't stop instance " << id << ": not started.\n";
  1015. return;
  1016. }
  1017. P3DCInstance *inst = (*ii).second;
  1018. _instances.erase(ii);
  1019. delete inst;
  1020. // TODO: we don't currently have any way to stop just one instance
  1021. // of a multi-instance session. This will require a different
  1022. // Python interface than ShowBase.
  1023. terminate_session();
  1024. }
  1025. ////////////////////////////////////////////////////////////////////
  1026. // Function: P3DPythonRun::set_instance_info
  1027. // Access: Private
  1028. // Description: Sets some global information about the instance.
  1029. ////////////////////////////////////////////////////////////////////
  1030. void P3DPythonRun::
  1031. set_instance_info(P3DCInstance *inst, TiXmlElement *xinstance) {
  1032. const char *root_dir = xinstance->Attribute("root_dir");
  1033. if (root_dir == NULL) {
  1034. root_dir = "";
  1035. }
  1036. const char *super_mirror = xinstance->Attribute("super_mirror");
  1037. if (super_mirror == NULL) {
  1038. super_mirror = "";
  1039. }
  1040. PyObject *result = PyObject_CallMethod
  1041. (_runner, (char *)"setInstanceInfo", (char *)"ss", root_dir, super_mirror);
  1042. if (result == NULL) {
  1043. PyErr_Print();
  1044. if (_interactive_console) {
  1045. run_interactive_console();
  1046. }
  1047. exit(1);
  1048. }
  1049. Py_XDECREF(result);
  1050. }
  1051. ////////////////////////////////////////////////////////////////////
  1052. // Function: P3DPythonRun::add_package_info
  1053. // Access: Private
  1054. // Description: Adds some information about a pre-loaded package.
  1055. ////////////////////////////////////////////////////////////////////
  1056. void P3DPythonRun::
  1057. add_package_info(P3DCInstance *inst, TiXmlElement *xpackage) {
  1058. const char *name = xpackage->Attribute("name");
  1059. const char *platform = xpackage->Attribute("platform");
  1060. const char *version = xpackage->Attribute("version");
  1061. const char *host = xpackage->Attribute("host");
  1062. const char *host_dir = xpackage->Attribute("host_dir");
  1063. if (name == NULL || host == NULL) {
  1064. return;
  1065. }
  1066. if (version == NULL) {
  1067. version = "";
  1068. }
  1069. if (platform == NULL) {
  1070. platform = "";
  1071. }
  1072. if (host_dir == NULL) {
  1073. host_dir = "";
  1074. }
  1075. PyObject *result = PyObject_CallMethod
  1076. (_runner, (char *)"addPackageInfo", (char *)"sssss",
  1077. name, platform, version, host, host_dir);
  1078. if (result == NULL) {
  1079. PyErr_Print();
  1080. if (_interactive_console) {
  1081. run_interactive_console();
  1082. }
  1083. exit(1);
  1084. }
  1085. Py_XDECREF(result);
  1086. }
  1087. ////////////////////////////////////////////////////////////////////
  1088. // Function: P3DPythonRun::set_p3d_filename
  1089. // Access: Private
  1090. // Description: Sets the startup filename and tokens for the
  1091. // indicated instance.
  1092. ////////////////////////////////////////////////////////////////////
  1093. void P3DPythonRun::
  1094. set_p3d_filename(P3DCInstance *inst, TiXmlElement *xfparams) {
  1095. string p3d_filename;
  1096. const char *p3d_filename_c = xfparams->Attribute("p3d_filename");
  1097. if (p3d_filename_c != NULL) {
  1098. p3d_filename = p3d_filename_c;
  1099. }
  1100. int p3d_offset = 0;
  1101. xfparams->Attribute("p3d_offset", &p3d_offset);
  1102. PyObject *token_list = PyList_New(0);
  1103. TiXmlElement *xtoken = xfparams->FirstChildElement("token");
  1104. while (xtoken != NULL) {
  1105. string keyword, value;
  1106. const char *keyword_c = xtoken->Attribute("keyword");
  1107. if (keyword_c != NULL) {
  1108. keyword = keyword_c;
  1109. }
  1110. const char *value_c = xtoken->Attribute("value");
  1111. if (value_c != NULL) {
  1112. value = value_c;
  1113. }
  1114. PyObject *tuple = Py_BuildValue("(ss)", keyword.c_str(),
  1115. value.c_str());
  1116. PyList_Append(token_list, tuple);
  1117. Py_DECREF(tuple);
  1118. xtoken = xtoken->NextSiblingElement("token");
  1119. }
  1120. PyObject *arg_list = PyList_New(0);
  1121. TiXmlElement *xarg = xfparams->FirstChildElement("arg");
  1122. while (xarg != NULL) {
  1123. string value;
  1124. const char *value_c = xarg->Attribute("value");
  1125. if (value_c != NULL) {
  1126. value = value_c;
  1127. }
  1128. PyObject *str = Py_BuildValue("s", value.c_str());
  1129. PyList_Append(arg_list, str);
  1130. Py_DECREF(str);
  1131. xarg = xarg->NextSiblingElement("arg");
  1132. }
  1133. PyObject *result = PyObject_CallMethod
  1134. (_runner, (char *)"setP3DFilename", (char *)"sOOiii", p3d_filename.c_str(),
  1135. token_list, arg_list, inst->get_instance_id(), _interactive_console, p3d_offset);
  1136. Py_DECREF(token_list);
  1137. Py_DECREF(arg_list);
  1138. if (result == NULL) {
  1139. PyErr_Print();
  1140. if (_interactive_console) {
  1141. run_interactive_console();
  1142. }
  1143. exit(1);
  1144. }
  1145. Py_XDECREF(result);
  1146. }
  1147. ////////////////////////////////////////////////////////////////////
  1148. // Function: P3DPythonRun::setup_window
  1149. // Access: Private
  1150. // Description: Sets the window parameters for the indicated instance.
  1151. ////////////////////////////////////////////////////////////////////
  1152. void P3DPythonRun::
  1153. setup_window(int id, TiXmlElement *xwparams) {
  1154. Instances::iterator ii = _instances.find(id);
  1155. if (ii == _instances.end()) {
  1156. nout << "Can't setup window for " << id << ": not started.\n";
  1157. return;
  1158. }
  1159. P3DCInstance *inst = (*ii).second;
  1160. setup_window(inst, xwparams);
  1161. }
  1162. ////////////////////////////////////////////////////////////////////
  1163. // Function: P3DPythonRun::setup_window
  1164. // Access: Private
  1165. // Description: Sets the window parameters for the indicated instance.
  1166. ////////////////////////////////////////////////////////////////////
  1167. void P3DPythonRun::
  1168. setup_window(P3DCInstance *inst, TiXmlElement *xwparams) {
  1169. string window_type;
  1170. const char *window_type_c = xwparams->Attribute("window_type");
  1171. if (window_type_c != NULL) {
  1172. window_type = window_type_c;
  1173. }
  1174. int win_x, win_y, win_width, win_height;
  1175. xwparams->Attribute("win_x", &win_x);
  1176. xwparams->Attribute("win_y", &win_y);
  1177. xwparams->Attribute("win_width", &win_width);
  1178. xwparams->Attribute("win_height", &win_height);
  1179. PT(WindowHandle) parent_window_handle;
  1180. #ifdef _WIN32
  1181. int hwnd;
  1182. if (xwparams->Attribute("parent_hwnd", &hwnd)) {
  1183. parent_window_handle = NativeWindowHandle::make_win((HWND)hwnd);
  1184. }
  1185. #elif __APPLE__
  1186. // On Mac, we don't parent windows directly to the browser; instead,
  1187. // we have to go through this subprocess-window nonsense.
  1188. const char *subprocess_window = xwparams->Attribute("subprocess_window");
  1189. if (subprocess_window != NULL) {
  1190. Filename filename = Filename::from_os_specific(subprocess_window);
  1191. parent_window_handle = NativeWindowHandle::make_subprocess(filename);
  1192. }
  1193. #elif defined(HAVE_X11)
  1194. // Use stringstream to decode the "long" attribute.
  1195. const char *parent_cstr = xwparams->Attribute("parent_xwindow");
  1196. if (parent_cstr != NULL) {
  1197. long window;
  1198. istringstream strm(parent_cstr);
  1199. strm >> window;
  1200. parent_window_handle = NativeWindowHandle::make_x11((Window)window);
  1201. }
  1202. #endif
  1203. PyObject *py_handle = Py_None;
  1204. if (parent_window_handle != NULL) {
  1205. // We have a valid parent WindowHandle, but replace it with a
  1206. // P3DWindowHandle so we can get the callbacks.
  1207. parent_window_handle = new P3DWindowHandle(this, inst, *parent_window_handle);
  1208. inst->_parent_window_handle = parent_window_handle;
  1209. // Also pass this P3DWindowHandle object down into Panda, via the
  1210. // setupWindow() call. For this, we need to create a Python
  1211. // wrapper objcet.
  1212. parent_window_handle->ref();
  1213. py_handle = DTool_CreatePyInstanceTyped(parent_window_handle, Dtool_WindowHandle, true, false, parent_window_handle->get_type_index());
  1214. }
  1215. Py_INCREF(py_handle);
  1216. // TODO: direct this into the particular instance. This will
  1217. // require a specialized ShowBase replacement.
  1218. PyObject *result = PyObject_CallMethod
  1219. (_runner, (char *)"setupWindow", (char *)"siiiiO", window_type.c_str(),
  1220. win_x, win_y, win_width, win_height, py_handle);
  1221. Py_DECREF(py_handle);
  1222. if (result == NULL) {
  1223. PyErr_Print();
  1224. if (_interactive_console) {
  1225. run_interactive_console();
  1226. }
  1227. exit(1);
  1228. }
  1229. Py_XDECREF(result);
  1230. }
  1231. ////////////////////////////////////////////////////////////////////
  1232. // Function: P3DPythonRun::send_windows_message
  1233. // Access: Public
  1234. // Description: This is used to deliver a windows keyboard message to
  1235. // the Panda process from the parent process, a
  1236. // necessary hack on Vista.
  1237. ////////////////////////////////////////////////////////////////////
  1238. void P3DPythonRun::
  1239. send_windows_message(int id, unsigned int msg, int wparam, int lparam) {
  1240. Instances::iterator ii = _instances.find(id);
  1241. if (ii == _instances.end()) {
  1242. return;
  1243. }
  1244. P3DCInstance *inst = (*ii).second;
  1245. if (inst->_parent_window_handle != (WindowHandle *)NULL) {
  1246. inst->_parent_window_handle->send_windows_message(msg, wparam, lparam);
  1247. }
  1248. }
  1249. ////////////////////////////////////////////////////////////////////
  1250. // Function: P3DPythonRun::terminate_session
  1251. // Access: Private
  1252. // Description: Stops all currently-running instances.
  1253. ////////////////////////////////////////////////////////////////////
  1254. void P3DPythonRun::
  1255. terminate_session() {
  1256. Instances::iterator ii;
  1257. for (ii = _instances.begin(); ii != _instances.end(); ++ii) {
  1258. P3DCInstance *inst = (*ii).second;
  1259. delete inst;
  1260. }
  1261. _instances.clear();
  1262. if (!_session_terminated) {
  1263. if (_taskMgr != NULL) {
  1264. PyObject *result = PyObject_CallMethod(_taskMgr, (char *)"stop", (char *)"");
  1265. if (result == NULL) {
  1266. PyErr_Print();
  1267. } else {
  1268. Py_DECREF(result);
  1269. }
  1270. }
  1271. _session_terminated = true;
  1272. }
  1273. }
  1274. ////////////////////////////////////////////////////////////////////
  1275. // Function: P3DPythonRun::pyobj_to_xml
  1276. // Access: Private
  1277. // Description: Converts the indicated PyObject to the appropriate
  1278. // XML representation of a P3D_value type, and returns a
  1279. // freshly-allocated TiXmlElement.
  1280. ////////////////////////////////////////////////////////////////////
  1281. TiXmlElement *P3DPythonRun::
  1282. pyobj_to_xml(PyObject *value) {
  1283. TiXmlElement *xvalue = new TiXmlElement("value");
  1284. if (value == Py_None) {
  1285. // None.
  1286. xvalue->SetAttribute("type", "none");
  1287. } else if (PyBool_Check(value)) {
  1288. // A bool value.
  1289. xvalue->SetAttribute("type", "bool");
  1290. xvalue->SetAttribute("value", PyObject_IsTrue(value));
  1291. } else if (PyInt_Check(value)) {
  1292. // A plain integer value.
  1293. xvalue->SetAttribute("type", "int");
  1294. xvalue->SetAttribute("value", PyInt_AsLong(value));
  1295. } else if (PyLong_Check(value)) {
  1296. // A long integer value. This gets converted either as an integer
  1297. // or as a floating-point type, whichever fits.
  1298. long lvalue = PyLong_AsLong(value);
  1299. if (PyErr_Occurred()) {
  1300. // It won't fit as an integer; make it a double.
  1301. PyErr_Clear();
  1302. xvalue->SetAttribute("type", "float");
  1303. xvalue->SetDoubleAttribute("value", PyLong_AsDouble(value));
  1304. } else {
  1305. // It fits as an integer.
  1306. xvalue->SetAttribute("type", "int");
  1307. xvalue->SetAttribute("value", lvalue);
  1308. }
  1309. } else if (PyFloat_Check(value)) {
  1310. // A floating-point value.
  1311. xvalue->SetAttribute("type", "float");
  1312. xvalue->SetDoubleAttribute("value", PyFloat_AsDouble(value));
  1313. } else if (PyUnicode_Check(value)) {
  1314. // A unicode value. Convert to utf-8 for the XML encoding.
  1315. xvalue->SetAttribute("type", "string");
  1316. PyObject *as_str = PyUnicode_AsUTF8String(value);
  1317. if (as_str != NULL) {
  1318. char *buffer;
  1319. Py_ssize_t length;
  1320. if (PyString_AsStringAndSize(as_str, &buffer, &length) != -1) {
  1321. string str(buffer, length);
  1322. xvalue->SetAttribute("value", str);
  1323. }
  1324. Py_DECREF(as_str);
  1325. }
  1326. } else if (PyString_Check(value)) {
  1327. // A string value.
  1328. xvalue->SetAttribute("type", "string");
  1329. char *buffer;
  1330. Py_ssize_t length;
  1331. if (PyString_AsStringAndSize(value, &buffer, &length) != -1) {
  1332. string str(buffer, length);
  1333. xvalue->SetAttribute("value", str);
  1334. }
  1335. } else if (PyTuple_Check(value)) {
  1336. // An immutable sequence. Pass it as a concrete.
  1337. xvalue->SetAttribute("type", "concrete_sequence");
  1338. Py_ssize_t length = PySequence_Length(value);
  1339. for (Py_ssize_t i = 0; i < length; ++i) {
  1340. PyObject *item = PySequence_GetItem(value, i);
  1341. if (item != NULL) {
  1342. xvalue->LinkEndChild(pyobj_to_xml(item));
  1343. Py_DECREF(item);
  1344. }
  1345. }
  1346. } else if (PyObject_IsInstance(value, _concrete_struct_class)) {
  1347. // This is a ConcreteStruct.
  1348. xvalue->SetAttribute("type", "concrete_struct");
  1349. PyObject *items = PyObject_CallMethod(value, (char *)"getConcreteProperties", (char *)"");
  1350. if (items == NULL) {
  1351. PyErr_Print();
  1352. return xvalue;
  1353. }
  1354. Py_ssize_t length = PySequence_Length(items);
  1355. for (Py_ssize_t i = 0; i < length; ++i) {
  1356. PyObject *item = PySequence_GetItem(items, i);
  1357. if (item != NULL) {
  1358. PyObject *a = PySequence_GetItem(item, 0);
  1359. if (a != NULL) {
  1360. PyObject *b = PySequence_GetItem(item, 1);
  1361. if (b != NULL) {
  1362. TiXmlElement *xitem = pyobj_to_xml(b);
  1363. Py_DECREF(b);
  1364. PyObject *as_str;
  1365. if (PyUnicode_Check(a)) {
  1366. // The key is a unicode value.
  1367. as_str = PyUnicode_AsUTF8String(a);
  1368. } else {
  1369. // The key is a string value or something else. Make it
  1370. // a string.
  1371. as_str = PyObject_Str(a);
  1372. }
  1373. char *buffer;
  1374. Py_ssize_t length;
  1375. if (PyString_AsStringAndSize(as_str, &buffer, &length) != -1) {
  1376. string str(buffer, length);
  1377. xitem->SetAttribute("key", str);
  1378. }
  1379. Py_DECREF(as_str);
  1380. xvalue->LinkEndChild(xitem);
  1381. }
  1382. Py_DECREF(a);
  1383. }
  1384. Py_DECREF(item);
  1385. }
  1386. }
  1387. // We've already avoided errors in the above code; clear the error
  1388. // flag.
  1389. PyErr_Clear();
  1390. Py_DECREF(items);
  1391. } else if (PyObject_IsInstance(value, _undefined_object_class)) {
  1392. // This is an UndefinedObject.
  1393. xvalue->SetAttribute("type", "undefined");
  1394. } else if (PyObject_IsInstance(value, _browser_object_class)) {
  1395. // This is a BrowserObject, a reference to an object that actually
  1396. // exists in the host namespace. So, pass up the appropriate
  1397. // object ID.
  1398. PyObject *objectId = PyObject_GetAttrString(value, (char *)"_BrowserObject__objectId");
  1399. if (objectId != NULL) {
  1400. int object_id = PyInt_AsLong(objectId);
  1401. xvalue->SetAttribute("type", "browser");
  1402. xvalue->SetAttribute("object_id", object_id);
  1403. Py_DECREF(objectId);
  1404. }
  1405. } else {
  1406. // Some other kind of object. Make it a generic Python object.
  1407. // This is more expensive for the caller to deal with--it requires
  1408. // a back-and-forth across the XML pipe--but it's much more
  1409. // general.
  1410. int object_id = _next_sent_id;
  1411. ++_next_sent_id;
  1412. bool inserted = _sent_objects.insert(SentObjects::value_type(object_id, value)).second;
  1413. while (!inserted) {
  1414. // Hmm, we must have cycled around the entire int space? Either
  1415. // that, or there's a logic bug somewhere. Assume the former,
  1416. // and keep looking for an empty slot.
  1417. object_id = _next_sent_id;
  1418. ++_next_sent_id;
  1419. inserted = _sent_objects.insert(SentObjects::value_type(object_id, value)).second;
  1420. }
  1421. // Now that it's stored in the map, increment its reference count.
  1422. Py_INCREF(value);
  1423. xvalue->SetAttribute("type", "python");
  1424. xvalue->SetAttribute("object_id", object_id);
  1425. }
  1426. return xvalue;
  1427. }
  1428. ////////////////////////////////////////////////////////////////////
  1429. // Function: P3DPythonRun::xml_to_pyobj
  1430. // Access: Private
  1431. // Description: Converts the XML representation of a P3D_value type
  1432. // into the equivalent Python object and returns it.
  1433. ////////////////////////////////////////////////////////////////////
  1434. PyObject *P3DPythonRun::
  1435. xml_to_pyobj(TiXmlElement *xvalue) {
  1436. const char *type = xvalue->Attribute("type");
  1437. if (strcmp(type, "none") == 0) {
  1438. return Py_BuildValue("");
  1439. } else if (strcmp(type, "bool") == 0) {
  1440. int value;
  1441. if (xvalue->QueryIntAttribute("value", &value) == TIXML_SUCCESS) {
  1442. return PyBool_FromLong(value);
  1443. }
  1444. } else if (strcmp(type, "int") == 0) {
  1445. int value;
  1446. if (xvalue->QueryIntAttribute("value", &value) == TIXML_SUCCESS) {
  1447. return PyInt_FromLong(value);
  1448. }
  1449. } else if (strcmp(type, "float") == 0) {
  1450. double value;
  1451. if (xvalue->QueryDoubleAttribute("value", &value) == TIXML_SUCCESS) {
  1452. return PyFloat_FromDouble(value);
  1453. }
  1454. } else if (strcmp(type, "string") == 0) {
  1455. // Using the string form here instead of the char * form, so we
  1456. // don't get tripped up on embedded null characters.
  1457. const string *value = xvalue->Attribute(string("value"));
  1458. if (value != NULL) {
  1459. return PyString_FromStringAndSize(value->data(), value->length());
  1460. }
  1461. } else if (strcmp(type, "undefined") == 0) {
  1462. Py_INCREF(_undefined);
  1463. return _undefined;
  1464. } else if (strcmp(type, "browser") == 0) {
  1465. int object_id;
  1466. if (xvalue->QueryIntAttribute("object_id", &object_id) == TIXML_SUCCESS) {
  1467. // Construct a new BrowserObject wrapper around this object.
  1468. return PyObject_CallFunction(_browser_object_class, (char *)"Oi",
  1469. _runner, object_id);
  1470. }
  1471. } else if (strcmp(type, "concrete_sequence") == 0) {
  1472. // Receive a concrete sequence as a tuple.
  1473. PyObject *list = PyList_New(0);
  1474. TiXmlElement *xitem = xvalue->FirstChildElement("value");
  1475. while (xitem != NULL) {
  1476. PyObject *item = xml_to_pyobj(xitem);
  1477. if (item != NULL) {
  1478. PyList_Append(list, item);
  1479. Py_DECREF(item);
  1480. }
  1481. xitem = xitem->NextSiblingElement("value");
  1482. }
  1483. PyObject *result = PyList_AsTuple(list);
  1484. Py_DECREF(list);
  1485. return result;
  1486. } else if (strcmp(type, "concrete_struct") == 0) {
  1487. // Receive a concrete struct as a new ConcreteStruct instance.
  1488. PyObject *obj = PyObject_CallFunction(_concrete_struct_class, (char *)"");
  1489. if (obj != NULL) {
  1490. TiXmlElement *xitem = xvalue->FirstChildElement("value");
  1491. while (xitem != NULL) {
  1492. const char *key = xitem->Attribute("key");
  1493. if (key != NULL) {
  1494. PyObject *item = xml_to_pyobj(xitem);
  1495. if (item != NULL) {
  1496. PyObject_SetAttrString(obj, (char *)key, item);
  1497. Py_DECREF(item);
  1498. }
  1499. }
  1500. xitem = xitem->NextSiblingElement("value");
  1501. }
  1502. return obj;
  1503. }
  1504. } else if (strcmp(type, "python") == 0) {
  1505. int object_id;
  1506. if (xvalue->QueryIntAttribute("object_id", &object_id) == TIXML_SUCCESS) {
  1507. SentObjects::iterator si = _sent_objects.find(object_id);
  1508. PyObject *result;
  1509. if (si == _sent_objects.end()) {
  1510. // Hmm, the parent process gave us a bogus object ID.
  1511. result = _undefined;
  1512. } else {
  1513. result = (*si).second;
  1514. }
  1515. Py_INCREF(result);
  1516. return result;
  1517. }
  1518. }
  1519. // Something went wrong in decoding.
  1520. PyObject *result = _undefined;
  1521. Py_INCREF(result);
  1522. return result;
  1523. }
  1524. ////////////////////////////////////////////////////////////////////
  1525. // Function: P3DPythonRun::rt_thread_run
  1526. // Access: Private
  1527. // Description: The main function for the read thread.
  1528. ////////////////////////////////////////////////////////////////////
  1529. void P3DPythonRun::
  1530. rt_thread_run() {
  1531. while (_read_thread_continue) {
  1532. TiXmlDocument *doc = read_xml(_pipe_read, nout);
  1533. if (doc == NULL) {
  1534. // Some error on reading. Abort.
  1535. _program_continue = false;
  1536. return;
  1537. }
  1538. // Successfully read an XML document.
  1539. // Check for one special case: the "exit" command means we shut
  1540. // down the read thread along with everything else.
  1541. TiXmlElement *xcommand = doc->FirstChildElement("command");
  1542. if (xcommand != NULL) {
  1543. const char *cmd = xcommand->Attribute("cmd");
  1544. if (cmd != NULL) {
  1545. if (strcmp(cmd, "exit") == 0) {
  1546. _read_thread_continue = false;
  1547. }
  1548. }
  1549. }
  1550. // Feed the command up to the parent.
  1551. ACQUIRE_LOCK(_commands_lock);
  1552. _commands.push_back(doc);
  1553. RELEASE_LOCK(_commands_lock);
  1554. }
  1555. }
  1556. ////////////////////////////////////////////////////////////////////
  1557. // Function: P3DPythonRun::P3DWindowHandle::Constructor
  1558. // Access: Public
  1559. // Description:
  1560. ////////////////////////////////////////////////////////////////////
  1561. P3DPythonRun::P3DWindowHandle::
  1562. P3DWindowHandle(P3DPythonRun *p3dpython, P3DCInstance *inst,
  1563. const WindowHandle &copy) :
  1564. WindowHandle(copy),
  1565. _p3dpython(p3dpython),
  1566. _inst(inst),
  1567. _child_count(0)
  1568. {
  1569. }
  1570. ////////////////////////////////////////////////////////////////////
  1571. // Function: P3DPythonRun::P3DWindowHandle::attach_child
  1572. // Access: Public, Virtual
  1573. // Description: Called on a parent handle to indicate a child
  1574. // window's intention to attach itself.
  1575. ////////////////////////////////////////////////////////////////////
  1576. void P3DPythonRun::P3DWindowHandle::
  1577. attach_child(WindowHandle *child) {
  1578. WindowHandle::attach_child(child);
  1579. ++_child_count;
  1580. if (_child_count == 1) {
  1581. // When the first child window is attached, we tell the plugin.
  1582. _p3dpython->set_window_open(_inst, true);
  1583. }
  1584. }
  1585. ////////////////////////////////////////////////////////////////////
  1586. // Function: P3DPythonRun::P3DWindowHandle::detach_child
  1587. // Access: Public, Virtual
  1588. // Description: Called on a parent handle to indicate a child
  1589. // window's intention to detach itself.
  1590. ////////////////////////////////////////////////////////////////////
  1591. void P3DPythonRun::P3DWindowHandle::
  1592. detach_child(WindowHandle *child) {
  1593. WindowHandle::detach_child(child);
  1594. --_child_count;
  1595. if (_child_count == 0) {
  1596. // When the last child window is detached, we tell the plugin.
  1597. _p3dpython->set_window_open(_inst, false);
  1598. }
  1599. }
  1600. ////////////////////////////////////////////////////////////////////
  1601. // Function: P3DPythonRun::P3DWindowHandle::request_keyboard_focus
  1602. // Access: Public, Virtual
  1603. // Description: Called on a parent handle to indicate a child
  1604. // window's wish to receive keyboard button events.
  1605. ////////////////////////////////////////////////////////////////////
  1606. void P3DPythonRun::P3DWindowHandle::
  1607. request_keyboard_focus(WindowHandle *child) {
  1608. WindowHandle::request_keyboard_focus(child);
  1609. _p3dpython->request_keyboard_focus(_inst);
  1610. }