p3dPythonRun.cxx 59 KB

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