IPCPlayerApp.cpp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  1. //
  2. // Copyright (c) 2014-2016 THUNDERBEAST GAMES LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. #include <Atomic/Core/CoreEvents.h>//
  22. #include <Atomic/IO/IOEvents.h>
  23. #include <Atomic/Input/InputEvents.h>
  24. #include <Atomic/Graphics/Graphics.h>
  25. #include <Atomic/Graphics/GraphicsEvents.h>
  26. #include <Atomic/IPC/IPCEvents.h>
  27. #include <AtomicJS/Javascript/JSIPCEvents.h>
  28. #include "IPCPlayerAppEvents.h"
  29. #include <Atomic/Engine/Engine.h>
  30. #include <Atomic/IPC/IPC.h>
  31. #include <AtomicJS/Javascript/Javascript.h>
  32. #include <Atomic/UI/SystemUI/DebugHud.h>
  33. #include "IPCPlayerApp.h"
  34. #include <stdio.h>
  35. namespace Atomic
  36. {
  37. IPCPlayerApp *arobj = NULL;
  38. void do_reconnect() // hack to call object method
  39. {
  40. if (arobj)
  41. arobj->Reconnect();
  42. }
  43. #ifdef ATOMIC_PLATFORM_WINDOWS
  44. /*
  45. * Example debug transport using a Windows TCP socket
  46. *
  47. * Provides a TCP server socket which a debug client can connect to.
  48. * After that data is just passed through.
  49. *
  50. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms737593(v=vs.85).aspx
  51. *
  52. * Compiling 'duk' with debugger support using MSVC (Visual Studio):
  53. *
  54. * > python2 tools\configure.py \
  55. * --output-directory prep
  56. * -DDUK_USE_DEBUGGER_SUPPORT -DDUK_USE_INTERRUPT_COUNTER
  57. * > cl /W3 /O2 /Feduk.exe \
  58. * /DDUK_CMDLINE_DEBUGGER_SUPPORT
  59. * /Iexamples\debug-trans-socket /Iprep
  60. * examples\cmdline\duk_cmdline.c
  61. * examples\debug-trans-socket\duk_trans_socket_windows.c
  62. * prep\duktape.c
  63. *
  64. * With MinGW:
  65. *
  66. * $ python2 tools\configure.py \
  67. * --output-directory prep
  68. * -DDUK_USE_DEBUGGER_SUPPORT -DDUK_USE_INTERRUPT_COUNTER
  69. * $ gcc -oduk.exe -Wall -O2 \
  70. * -DDUK_CMDLINE_DEBUGGER_SUPPORT \
  71. * -Iexamples/debug-trans-socket -Iprep \
  72. * examples/cmdline/duk_cmdline.c \
  73. * examples/debug-trans-socket/duk_trans_socket_windows.c \
  74. * prep/duktape.c -lm -lws2_32
  75. */
  76. #undef UNICODE
  77. #if !defined(WIN32_LEAN_AND_MEAN)
  78. #define WIN32_LEAN_AND_MEAN
  79. #endif
  80. /* MinGW workaround for missing getaddrinfo() etc:
  81. * http://programmingrants.blogspot.fi/2009/09/tips-on-undefined-reference-to.html
  82. */
  83. #if defined(__MINGW32__) || defined(__MINGW64__)
  84. #if !defined(_WIN32_WINNT)
  85. #define _WIN32_WINNT 0x0501
  86. #endif
  87. #endif
  88. #include <windows.h>
  89. #include <winsock2.h>
  90. #include <ws2tcpip.h>
  91. #include <stdio.h>
  92. #include <string.h>
  93. #include "duktape.h"
  94. #if defined(_MSC_VER)
  95. #pragma comment (lib, "Ws2_32.lib")
  96. #endif
  97. #if !defined(DUK_DEBUG_PORT)
  98. #define DUK_DEBUG_PORT 9091
  99. #endif
  100. #if !defined(DUK_DEBUG_ADDRESS)
  101. #define DUK_DEBUG_ADDRESS "0.0.0.0"
  102. #endif
  103. #define DUK__STRINGIFY_HELPER(x) #x
  104. #define DUK__STRINGIFY(x) DUK__STRINGIFY_HELPER(x)
  105. #if 0
  106. #define DEBUG_PRINTS
  107. #endif
  108. static SOCKET server_sock = INVALID_SOCKET;
  109. static SOCKET client_sock = INVALID_SOCKET;
  110. static int wsa_inited = 0;
  111. /*
  112. * Transport init and finish
  113. */
  114. void duk_trans_socket_init(void) {
  115. WSADATA wsa_data;
  116. struct addrinfo hints;
  117. struct addrinfo *result = NULL;
  118. int rc;
  119. memset((void *) &wsa_data, 0, sizeof(wsa_data));
  120. memset((void *) &hints, 0, sizeof(hints));
  121. rc = WSAStartup(MAKEWORD(2, 2), &wsa_data);
  122. if (rc != 0) {
  123. fprintf(stderr, "%s: WSAStartup() failed: %d\n", __FILE__, rc);
  124. fflush(stderr);
  125. goto fail;
  126. }
  127. wsa_inited = 1;
  128. hints.ai_family = AF_UNSPEC;
  129. hints.ai_socktype = SOCK_STREAM;
  130. hints.ai_protocol = IPPROTO_TCP;
  131. hints.ai_flags = AI_PASSIVE;
  132. rc = getaddrinfo(DUK_DEBUG_ADDRESS, DUK__STRINGIFY(DUK_DEBUG_PORT), &hints, &result);
  133. if (rc != 0) {
  134. fprintf(stderr, "%s: getaddrinfo() failed: %d\n", __FILE__, rc);
  135. fflush(stderr);
  136. goto fail;
  137. }
  138. server_sock = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
  139. if (server_sock == INVALID_SOCKET) {
  140. fprintf(stderr, "%s: socket() failed with error: %ld\n",
  141. __FILE__, (long) WSAGetLastError());
  142. fflush(stderr);
  143. goto fail;
  144. }
  145. rc = bind(server_sock, result->ai_addr, (int) result->ai_addrlen);
  146. if (rc == SOCKET_ERROR) {
  147. fprintf(stderr, "%s: bind() failed with error: %ld\n",
  148. __FILE__, (long) WSAGetLastError());
  149. fflush(stderr);
  150. goto fail;
  151. }
  152. rc = listen(server_sock, SOMAXCONN);
  153. if (rc == SOCKET_ERROR) {
  154. fprintf(stderr, "%s: listen() failed with error: %ld\n",
  155. __FILE__, (long) WSAGetLastError());
  156. fflush(stderr);
  157. goto fail;
  158. }
  159. if (result != NULL) {
  160. freeaddrinfo(result);
  161. result = NULL;
  162. }
  163. return;
  164. fail:
  165. if (result != NULL) {
  166. freeaddrinfo(result);
  167. result = NULL;
  168. }
  169. if (server_sock != INVALID_SOCKET) {
  170. (void) closesocket(server_sock);
  171. server_sock = INVALID_SOCKET;
  172. }
  173. if (wsa_inited) {
  174. WSACleanup();
  175. wsa_inited = 0;
  176. }
  177. }
  178. void duk_trans_socket_finish(void) {
  179. if (client_sock != INVALID_SOCKET) {
  180. (void) closesocket(client_sock);
  181. client_sock = INVALID_SOCKET;
  182. }
  183. if (server_sock != INVALID_SOCKET) {
  184. (void) closesocket(server_sock);
  185. server_sock = INVALID_SOCKET;
  186. }
  187. if (wsa_inited) {
  188. WSACleanup();
  189. wsa_inited = 0;
  190. }
  191. // auto-restart
  192. do_reconnect();
  193. }
  194. void duk_trans_socket_waitconn(void) {
  195. if (server_sock == INVALID_SOCKET) {
  196. fprintf(stderr, "%s: no server socket, skip waiting for connection\n",
  197. __FILE__);
  198. fflush(stderr);
  199. return;
  200. }
  201. if (client_sock != INVALID_SOCKET) {
  202. (void) closesocket(client_sock);
  203. client_sock = INVALID_SOCKET;
  204. }
  205. fprintf(stderr, "Waiting for debug connection on port %d\n", (int) DUK_DEBUG_PORT);
  206. fflush(stderr);
  207. client_sock = accept(server_sock, NULL, NULL);
  208. if (client_sock == INVALID_SOCKET) {
  209. fprintf(stderr, "%s: accept() failed with error %ld, skip waiting for connection\n",
  210. __FILE__, (long) WSAGetLastError());
  211. fflush(stderr);
  212. goto fail;
  213. }
  214. fprintf(stderr, "Debug connection established\n");
  215. fflush(stderr);
  216. /* XXX: For now, close the listen socket because we won't accept new
  217. * connections anyway. A better implementation would allow multiple
  218. * debug attaches.
  219. */
  220. if (server_sock != INVALID_SOCKET) {
  221. (void) closesocket(server_sock);
  222. server_sock = INVALID_SOCKET;
  223. }
  224. return;
  225. fail:
  226. if (client_sock != INVALID_SOCKET) {
  227. (void) closesocket(client_sock);
  228. client_sock = INVALID_SOCKET;
  229. }
  230. }
  231. /*
  232. * Duktape callbacks
  233. */
  234. /* Duktape debug transport callback: (possibly partial) read. */
  235. duk_size_t duk_trans_socket_read_cb(void *udata, char *buffer, duk_size_t length) {
  236. int ret;
  237. (void) udata; /* not needed by the example */
  238. #if defined(DEBUG_PRINTS)
  239. fprintf(stderr, "%s: udata=%p, buffer=%p, length=%ld\n",
  240. __FUNCTION__, (void *) udata, (void *) buffer, (long) length);
  241. fflush(stderr);
  242. #endif
  243. if (client_sock == INVALID_SOCKET) {
  244. return 0;
  245. }
  246. if (length == 0) {
  247. /* This shouldn't happen. */
  248. fprintf(stderr, "%s: read request length == 0, closing connection\n",
  249. __FILE__);
  250. fflush(stderr);
  251. goto fail;
  252. }
  253. if (buffer == NULL) {
  254. /* This shouldn't happen. */
  255. fprintf(stderr, "%s: read request buffer == NULL, closing connection\n",
  256. __FILE__);
  257. fflush(stderr);
  258. goto fail;
  259. }
  260. /* In a production quality implementation there would be a sanity
  261. * timeout here to recover from "black hole" disconnects.
  262. */
  263. ret = recv(client_sock, (void *) buffer, (int) length, 0);
  264. if (ret < 0) {
  265. fprintf(stderr, "%s: debug read failed, error %d, closing connection\n",
  266. __FILE__, ret);
  267. fflush(stderr);
  268. goto fail;
  269. } else if (ret == 0) {
  270. fprintf(stderr, "%s: debug read failed, ret == 0 (EOF), closing connection\n",
  271. __FILE__);
  272. fflush(stderr);
  273. goto fail;
  274. } else if (ret > (int) length) {
  275. fprintf(stderr, "%s: debug read failed, ret too large (%ld > %ld), closing connection\n",
  276. __FILE__, (long) ret, (long) length);
  277. fflush(stderr);
  278. goto fail;
  279. }
  280. return (duk_size_t) ret;
  281. fail:
  282. if (client_sock != INVALID_SOCKET) {
  283. (void) closesocket(client_sock);
  284. client_sock = INVALID_SOCKET;
  285. }
  286. return 0;
  287. }
  288. /* Duktape debug transport callback: (possibly partial) write. */
  289. duk_size_t duk_trans_socket_write_cb(void *udata, const char *buffer, duk_size_t length) {
  290. int ret;
  291. (void) udata; /* not needed by the example */
  292. #if defined(DEBUG_PRINTS)
  293. fprintf(stderr, "%s: udata=%p, buffer=%p, length=%ld\n",
  294. __FUNCTION__, (void *) udata, (const void *) buffer, (long) length);
  295. fflush(stderr);
  296. #endif
  297. if (client_sock == INVALID_SOCKET) {
  298. return 0;
  299. }
  300. if (length == 0) {
  301. /* This shouldn't happen. */
  302. fprintf(stderr, "%s: write request length == 0, closing connection\n",
  303. __FILE__);
  304. fflush(stderr);
  305. goto fail;
  306. }
  307. if (buffer == NULL) {
  308. /* This shouldn't happen. */
  309. fprintf(stderr, "%s: write request buffer == NULL, closing connection\n",
  310. __FILE__);
  311. fflush(stderr);
  312. goto fail;
  313. }
  314. /* In a production quality implementation there would be a sanity
  315. * timeout here to recover from "black hole" disconnects.
  316. */
  317. ret = send(client_sock, (const void *) buffer, (int) length, 0);
  318. if (ret <= 0 || ret > (int) length) {
  319. fprintf(stderr, "%s: debug write failed, ret %d, closing connection\n",
  320. __FILE__, ret);
  321. fflush(stderr);
  322. goto fail;
  323. }
  324. return (duk_size_t) ret;
  325. fail:
  326. if (client_sock != INVALID_SOCKET) {
  327. (void) closesocket(INVALID_SOCKET);
  328. client_sock = INVALID_SOCKET;
  329. }
  330. return 0;
  331. }
  332. duk_size_t duk_trans_socket_peek_cb(void *udata) {
  333. u_long avail;
  334. int rc;
  335. (void) udata; /* not needed by the example */
  336. #if defined(DEBUG_PRINTS)
  337. fprintf(stderr, "%s: udata=%p\n", __FUNCTION__, (void *) udata);
  338. fflush(stderr);
  339. #endif
  340. if (client_sock == INVALID_SOCKET) {
  341. return 0;
  342. }
  343. avail = 0;
  344. rc = ioctlsocket(client_sock, FIONREAD, &avail);
  345. if (rc != 0) {
  346. fprintf(stderr, "%s: ioctlsocket() returned %d, closing connection\n",
  347. __FILE__, rc);
  348. fflush(stderr);
  349. goto fail; /* also returns 0, which is correct */
  350. } else {
  351. if (avail == 0) {
  352. return 0; /* nothing to read */
  353. } else {
  354. return 1; /* something to read */
  355. }
  356. }
  357. /* never here */
  358. fail:
  359. if (client_sock != INVALID_SOCKET) {
  360. (void) closesocket(client_sock);
  361. client_sock = INVALID_SOCKET;
  362. }
  363. return 0;
  364. }
  365. void duk_trans_socket_read_flush_cb(void *udata) {
  366. (void) udata; /* not needed by the example */
  367. #if defined(DEBUG_PRINTS)
  368. fprintf(stderr, "%s: udata=%p\n", __FUNCTION__, (void *) udata);
  369. fflush(stderr);
  370. #endif
  371. /* Read flush: Duktape may not be making any more read calls at this
  372. * time. If the transport maintains a receive window, it can use a
  373. * read flush as a signal to update the window status to the remote
  374. * peer. A read flush is guaranteed to occur before Duktape stops
  375. * reading for a while; it may occur in other situations as well so
  376. * it's not a 100% reliable indication.
  377. */
  378. /* This TCP transport requires no read flush handling so ignore.
  379. * You can also pass a NULL to duk_debugger_attach() and not
  380. * implement this callback at all.
  381. */
  382. }
  383. void duk_trans_socket_write_flush_cb(void *udata) {
  384. (void) udata; /* not needed by the example */
  385. #if defined(DEBUG_PRINTS)
  386. fprintf(stderr, "%s: udata=%p\n", __FUNCTION__, (void *) udata);
  387. fflush(stderr);
  388. #endif
  389. /* Write flush. If the transport combines multiple writes
  390. * before actually sending, a write flush is an indication
  391. * to write out any pending bytes: Duktape may not be doing
  392. * any more writes on this occasion.
  393. */
  394. /* This TCP transport requires no write flush handling so ignore.
  395. * You can also pass a NULL to duk_debugger_attach() and not
  396. * implement this callback at all.
  397. */
  398. return;
  399. }
  400. #undef DUK__STRINGIFY_HELPER
  401. #undef DUK__STRINGIFY
  402. #else // OSX ad LINUX
  403. /*
  404. * Example debug transport using a Linux/Unix TCP socket
  405. *
  406. * Provides a TCP server socket which a debug client can connect to.
  407. * After that data is just passed through.
  408. */
  409. #include <stdio.h>
  410. #include <string.h>
  411. #include <sys/socket.h>
  412. #include <netinet/in.h>
  413. #include <unistd.h>
  414. #include <poll.h>
  415. #include <errno.h>
  416. #include <ThirdParty/Duktape/duktape.h>
  417. #if !defined(DUK_DEBUG_PORT)
  418. #define DUK_DEBUG_PORT 9091
  419. #endif
  420. #if 0
  421. #define DEBUG_PRINTS
  422. #endif
  423. static int server_sock = -1;
  424. static int client_sock = -1;
  425. /*
  426. * Transport init and finish
  427. */
  428. void duk_trans_socket_init(void) {
  429. struct sockaddr_in addr;
  430. int on;
  431. server_sock = socket(AF_INET, SOCK_STREAM, 0);
  432. if (server_sock < 0) {
  433. fprintf(stderr, "%s: failed to create server socket: %s\n",
  434. __FILE__, strerror(errno));
  435. fflush(stderr);
  436. goto fail;
  437. }
  438. on = 1;
  439. if (setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, (const char *) &on, sizeof(on)) < 0) {
  440. fprintf(stderr, "%s: failed to set SO_REUSEADDR for server socket: %s\n",
  441. __FILE__, strerror(errno));
  442. fflush(stderr);
  443. goto fail;
  444. }
  445. memset((void *) &addr, 0, sizeof(addr));
  446. addr.sin_family = AF_INET;
  447. addr.sin_addr.s_addr = INADDR_ANY;
  448. addr.sin_port = htons(DUK_DEBUG_PORT);
  449. if (bind(server_sock, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
  450. fprintf(stderr, "%s: failed to bind server socket: %s\n",
  451. __FILE__, strerror(errno));
  452. fflush(stderr);
  453. goto fail;
  454. }
  455. listen(server_sock, 1 /*backlog*/);
  456. return;
  457. fail:
  458. if (server_sock >= 0) {
  459. (void) close(server_sock);
  460. server_sock = -1;
  461. }
  462. }
  463. void duk_trans_socket_waitconn(void) {
  464. struct sockaddr_in addr;
  465. socklen_t sz;
  466. if (server_sock < 0) {
  467. fprintf(stderr, "%s: no server socket, skip waiting for connection\n",
  468. __FILE__);
  469. fflush(stderr);
  470. return;
  471. }
  472. if (client_sock >= 0) {
  473. (void) close(client_sock);
  474. client_sock = -1;
  475. }
  476. fprintf(stderr, "Waiting for debug connection on port %d\n", (int) DUK_DEBUG_PORT);
  477. fflush(stderr);
  478. sz = (socklen_t) sizeof(addr);
  479. client_sock = accept(server_sock, (struct sockaddr *) &addr, &sz);
  480. if (client_sock < 0) {
  481. fprintf(stderr, "%s: accept() failed, skip waiting for connection: %s\n",
  482. __FILE__, strerror(errno));
  483. fflush(stderr);
  484. goto fail;
  485. }
  486. fprintf(stderr, "Debug connection established\n");
  487. fflush(stderr);
  488. /* XXX: For now, close the listen socket because we won't accept new
  489. * connections anyway. A better implementation would allow multiple
  490. * debug attaches.
  491. */
  492. if (server_sock >= 0) {
  493. (void) close(server_sock);
  494. server_sock = -1;
  495. }
  496. return;
  497. fail:
  498. if (client_sock >= 0) {
  499. (void) close(client_sock);
  500. client_sock = -1;
  501. }
  502. }
  503. void duk_trans_socket_finish(void) {
  504. if (client_sock >= 0) {
  505. (void) close(client_sock);
  506. client_sock = -1;
  507. }
  508. if (server_sock >= 0) {
  509. (void) close(server_sock);
  510. server_sock = -1;
  511. }
  512. //
  513. // auto-restart
  514. do_reconnect();
  515. }
  516. /*
  517. * Duktape callbacks
  518. */
  519. /* Duktape debug transport callback: (possibly partial) read. */
  520. duk_size_t duk_trans_socket_read_cb(void *udata, char *buffer, duk_size_t length) {
  521. ssize_t ret;
  522. (void) udata; /* not needed by the example */
  523. #if defined(DEBUG_PRINTS)
  524. fprintf(stderr, "%s: udata=%p, buffer=%p, length=%ld\n",
  525. __func__, (void *) udata, (void *) buffer, (long) length);
  526. fflush(stderr);
  527. #endif
  528. if (client_sock < 0) {
  529. return 0;
  530. }
  531. if (length == 0) {
  532. /* This shouldn't happen. */
  533. fprintf(stderr, "%s: read request length == 0, closing connection\n",
  534. __FILE__);
  535. fflush(stderr);
  536. goto fail;
  537. }
  538. if (buffer == NULL) {
  539. /* This shouldn't happen. */
  540. fprintf(stderr, "%s: read request buffer == NULL, closing connection\n",
  541. __FILE__);
  542. fflush(stderr);
  543. goto fail;
  544. }
  545. /* In a production quality implementation there would be a sanity
  546. * timeout here to recover from "black hole" disconnects.
  547. */
  548. ret = read(client_sock, (void *) buffer, (size_t) length);
  549. if (ret < 0) {
  550. fprintf(stderr, "%s: debug read failed, closing connection: %s\n",
  551. __FILE__, strerror(errno));
  552. fflush(stderr);
  553. goto fail;
  554. } else if (ret == 0) {
  555. fprintf(stderr, "%s: debug read failed, ret == 0 (EOF), closing connection\n",
  556. __FILE__);
  557. fflush(stderr);
  558. goto fail;
  559. } else if (ret > (ssize_t) length) {
  560. fprintf(stderr, "%s: debug read failed, ret too large (%ld > %ld), closing connection\n",
  561. __FILE__, (long) ret, (long) length);
  562. fflush(stderr);
  563. goto fail;
  564. }
  565. return (duk_size_t) ret;
  566. fail:
  567. if (client_sock >= 0) {
  568. (void) close(client_sock);
  569. client_sock = -1;
  570. }
  571. return 0;
  572. }
  573. /* Duktape debug transport callback: (possibly partial) write. */
  574. duk_size_t duk_trans_socket_write_cb(void *udata, const char *buffer, duk_size_t length) {
  575. ssize_t ret;
  576. (void) udata; /* not needed by the example */
  577. #if defined(DEBUG_PRINTS)
  578. fprintf(stderr, "%s: udata=%p, buffer=%p, length=%ld\n",
  579. __func__, (void *) udata, (const void *) buffer, (long) length);
  580. fflush(stderr);
  581. #endif
  582. if (client_sock < 0) {
  583. return 0;
  584. }
  585. if (length == 0) {
  586. /* This shouldn't happen. */
  587. fprintf(stderr, "%s: write request length == 0, closing connection\n",
  588. __FILE__);
  589. fflush(stderr);
  590. goto fail;
  591. }
  592. if (buffer == NULL) {
  593. /* This shouldn't happen. */
  594. fprintf(stderr, "%s: write request buffer == NULL, closing connection\n",
  595. __FILE__);
  596. fflush(stderr);
  597. goto fail;
  598. }
  599. /* In a production quality implementation there would be a sanity
  600. * timeout here to recover from "black hole" disconnects.
  601. */
  602. ret = write(client_sock, (const void *) buffer, (size_t) length);
  603. if (ret <= 0 || ret > (ssize_t) length) {
  604. fprintf(stderr, "%s: debug write failed, closing connection: %s\n",
  605. __FILE__, strerror(errno));
  606. fflush(stderr);
  607. goto fail;
  608. }
  609. return (duk_size_t) ret;
  610. fail:
  611. if (client_sock >= 0) {
  612. (void) close(client_sock);
  613. client_sock = -1;
  614. }
  615. return 0;
  616. }
  617. duk_size_t duk_trans_socket_peek_cb(void *udata) {
  618. struct pollfd fds[1];
  619. int poll_rc;
  620. (void) udata; /* not needed by the example */
  621. #if defined(DEBUG_PRINTS)
  622. fprintf(stderr, "%s: udata=%p\n", __func__, (void *) udata);
  623. fflush(stderr);
  624. #endif
  625. if (client_sock < 0) {
  626. return 0;
  627. }
  628. fds[0].fd = client_sock;
  629. fds[0].events = POLLIN;
  630. fds[0].revents = 0;
  631. poll_rc = poll(fds, 1, 0);
  632. if (poll_rc < 0) {
  633. fprintf(stderr, "%s: poll returned < 0, closing connection: %s\n",
  634. __FILE__, strerror(errno));
  635. fflush(stderr);
  636. goto fail; /* also returns 0, which is correct */
  637. } else if (poll_rc > 1) {
  638. fprintf(stderr, "%s: poll returned > 1, treating like 1\n",
  639. __FILE__);
  640. fflush(stderr);
  641. return 1; /* should never happen */
  642. } else if (poll_rc == 0) {
  643. return 0; /* nothing to read */
  644. } else {
  645. return 1; /* something to read */
  646. }
  647. fail:
  648. if (client_sock >= 0) {
  649. (void) close(client_sock);
  650. client_sock = -1;
  651. }
  652. return 0;
  653. }
  654. void duk_trans_socket_read_flush_cb(void *udata) {
  655. (void) udata; /* not needed by the example */
  656. #if defined(DEBUG_PRINTS)
  657. fprintf(stderr, "%s: udata=%p\n", __func__, (void *) udata);
  658. fflush(stderr);
  659. #endif
  660. /* Read flush: Duktape may not be making any more read calls at this
  661. * time. If the transport maintains a receive window, it can use a
  662. * read flush as a signal to update the window status to the remote
  663. * peer. A read flush is guaranteed to occur before Duktape stops
  664. * reading for a while; it may occur in other situations as well so
  665. * it's not a 100% reliable indication.
  666. */
  667. /* This TCP transport requires no read flush handling so ignore.
  668. * You can also pass a NULL to duk_debugger_attach() and not
  669. * implement this callback at all.
  670. */
  671. }
  672. void duk_trans_socket_write_flush_cb(void *udata) {
  673. (void) udata; /* not needed by the example */
  674. #if defined(DEBUG_PRINTS)
  675. fprintf(stderr, "%s: udata=%p\n", __func__, (void *) udata);
  676. fflush(stderr);
  677. #endif
  678. /* Write flush. If the transport combines multiple writes
  679. * before actually sending, a write flush is an indication
  680. * to write out any pending bytes: Duktape may not be doing
  681. * any more writes on this occasion.
  682. */
  683. /* This TCP transport requires no write flush handling so ignore.
  684. * You can also pass a NULL to duk_debugger_attach() and not
  685. * implement this callback at all.
  686. */
  687. return;
  688. }
  689. #endif // OSX ad LINUX
  690. void debugger_detached (duk_context* ctx, void *udata) {
  691. fflush(stderr);
  692. /* Ensure socket is closed even when detach is initiated by Duktape
  693. * rather than debug client.
  694. */
  695. duk_trans_socket_finish();
  696. }
  697. // hack around oo programming, so a function can call a class method.
  698. void set_autoreconn ( IPCPlayerApp *someptr )
  699. {
  700. arobj = someptr;
  701. }
  702. IPCPlayerApp::IPCPlayerApp(Context* context) :
  703. PlayerApp(context),
  704. subprocess_(false),
  705. debugPlayer_(false),
  706. brokerActive_(false)
  707. {
  708. fd_[0] = INVALID_IPCHANDLE_VALUE;
  709. fd_[1] = INVALID_IPCHANDLE_VALUE;
  710. }
  711. IPCPlayerApp::~IPCPlayerApp()
  712. {
  713. }
  714. void IPCPlayerApp::Setup()
  715. {
  716. PlayerApp::Setup();
  717. // This should be configurable
  718. engineParameters_.InsertNew("LogLevel", LOG_DEBUG);
  719. ipc_ = new IPC(context_);
  720. context_->RegisterSubsystem(ipc_);
  721. }
  722. void IPCPlayerApp::ProcessArguments()
  723. {
  724. PlayerApp::ProcessArguments();
  725. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  726. if (!fileSystem)
  727. {
  728. ErrorExit("IPCPlayerApp::ProcessArguments FileSystem subsystem does not exist");
  729. }
  730. String resourcePrefix;
  731. engineParameters_["ResourcePrefixPaths"] = "";
  732. for (unsigned i = 0; i < arguments_.Size(); ++i)
  733. {
  734. if (arguments_[i].Length() > 1)
  735. {
  736. String argument = arguments_[i].ToLower();
  737. String value = i + 1 < arguments_.Size() ? arguments_[i + 1] : String::EMPTY;
  738. if (argument.StartsWith("--ipc-server=") || argument.StartsWith("--ipc-client="))
  739. {
  740. subprocess_ = true;
  741. }
  742. else if (argument == "--debug")
  743. {
  744. debugPlayer_ = true;
  745. }
  746. else if (argument == "--resourceprefix" && value.Length())
  747. {
  748. resourcePrefix = value;
  749. engineParameters_["ResourcePrefixPaths"] = resourcePrefix;
  750. }
  751. else if (argument == "--project" && value.Length())
  752. {
  753. value = AddTrailingSlash(value);
  754. AddEngineConfigSearchPath(value + "Settings/");
  755. // check that cache exists
  756. if (!fileSystem->DirExists(value + "Cache"))
  757. {
  758. ErrorExit("Project cache folder does not exist, projects must be loaded into the Atomic Editor at least once before using the --player command line mode");
  759. return;
  760. }
  761. #ifdef ATOMIC_DEV_BUILD
  762. String resourcePaths = ToString("%s/Resources/CoreData;%s/Resources/PlayerData;%sResources;%s;%sCache",
  763. ATOMIC_ROOT_SOURCE_DIR, ATOMIC_ROOT_SOURCE_DIR, value.CString(), value.CString(), value.CString());
  764. #else
  765. #ifdef __APPLE__
  766. if (!resourcePrefix.Length())
  767. {
  768. engineParameters_["ResourcePrefixPaths"] = fileSystem->GetProgramDir() + "../Resources";
  769. }
  770. #else
  771. if (!resourcePrefix.Length())
  772. {
  773. engineParameters_["ResourcePrefixPaths"] = fileSystem->GetProgramDir() + "Resources";
  774. }
  775. #endif
  776. String resourcePaths = ToString("CoreData;PlayerData;%s/;%s/Resources;%s;%sCache",
  777. value.CString(), value.CString(), value.CString(), value.CString());
  778. #endif
  779. ATOMIC_LOGINFOF("Adding ResourcePaths: %s", resourcePaths.CString());
  780. engineParameters_["ResourcePaths"] = resourcePaths;
  781. }
  782. }
  783. }
  784. // IPC client player should not auto exit if a subprocess
  785. if (subprocess_)
  786. engine_->SetAutoExit(false);
  787. }
  788. void IPCPlayerApp::Start()
  789. {
  790. if (subprocess_)
  791. {
  792. // do not execute main in the player app
  793. executeJSMain_ = false;
  794. }
  795. PlayerApp::Start();
  796. int id = -1;
  797. if (IPC::ProcessArguments(arguments_, id, fd_[0], fd_[1]))
  798. {
  799. SubscribeToEvent(E_IPCINITIALIZE, ATOMIC_HANDLER(IPCPlayerApp, HandleIPCInitialize));
  800. SubscribeToEvent(E_LOGMESSAGE, ATOMIC_HANDLER(IPCPlayerApp, HandleLogMessage));
  801. SubscribeToEvent(E_JSERROR, ATOMIC_HANDLER(IPCPlayerApp, HandleJSError));
  802. SubscribeToEvent(E_EXITREQUESTED, ATOMIC_HANDLER(IPCPlayerApp, HandleExitRequest));
  803. SubscribeToEvent(E_SCREENMODE, ATOMIC_HANDLER(IPCPlayerApp, HandlePlayerWindowChanged));
  804. SubscribeToEvent(E_WINDOWPOS, ATOMIC_HANDLER(IPCPlayerApp, HandlePlayerWindowChanged));
  805. SubscribeToEvent(E_UPDATESPAUSEDRESUMED, ATOMIC_HANDLER(IPCPlayerApp, HandleUpdatesPausedResumed));
  806. if (ipc_->InitWorker((unsigned)id, fd_[0], fd_[1]))
  807. {
  808. brokerActive_ = true;
  809. }
  810. else if (subprocess_)
  811. {
  812. ATOMIC_LOGERROR("IPCPlayerApp::Start() - Unable to initialize IPC Worker");
  813. }
  814. }
  815. if (subprocess_)
  816. {
  817. JSVM* vm = JSVM::GetJSVM(0);
  818. if (!vm->ExecuteMain())
  819. {
  820. SendEvent(E_EXITREQUESTED);
  821. }
  822. SubscribeToEvent(E_PLAYERQUIT, ATOMIC_HANDLER(IPCPlayerApp, HandleQuit));
  823. set_autoreconn (this); // for auto-reconnect
  824. }
  825. GetSubsystem<Graphics>()->RaiseWindow();
  826. if (debugPlayer_)
  827. {
  828. ATOMIC_LOGERROR("Starting Debugger");
  829. set_autoreconn (this); // for auto-reconnect
  830. Reconnect();
  831. }
  832. }
  833. void IPCPlayerApp::Reconnect()
  834. {
  835. duk_trans_socket_init();
  836. duk_trans_socket_waitconn();
  837. JSVM* vm = JSVM::GetJSVM(0);
  838. if(!vm) return;
  839. duk_context *ctx_ = vm->GetJSContext();
  840. if(!ctx_) return;
  841. duk_debugger_attach(ctx_,
  842. duk_trans_socket_read_cb,
  843. duk_trans_socket_write_cb,
  844. duk_trans_socket_peek_cb,
  845. duk_trans_socket_read_flush_cb,
  846. duk_trans_socket_write_flush_cb,
  847. NULL, // duk_debug_request_function - no custom application specific request functions
  848. debugger_detached,
  849. NULL);
  850. }
  851. void IPCPlayerApp::HandleQuit(StringHash eventType, VariantMap& eventData)
  852. {
  853. engine_->Exit();
  854. }
  855. void IPCPlayerApp::Stop()
  856. {
  857. PlayerApp::Stop();
  858. }
  859. void IPCPlayerApp::HandleIPCInitialize(StringHash eventType, VariantMap& eventData)
  860. {
  861. brokerActive_ = true;
  862. // If the parent application has a profile mode up, sync
  863. SystemUI::DebugHud* debugHud = GetSubsystem<SystemUI::DebugHud>();
  864. if (debugHud)
  865. {
  866. unsigned mode = eventData["debugHudMode"].GetUInt();
  867. // Only set if we haven't set the mode in player code
  868. if (mode && !debugHud->GetMode())
  869. {
  870. debugHud->SetMode(mode);
  871. debugHud->SetProfilerMode((DebugHudProfileMode)eventData["debugHudProfilerMode"].GetUInt());
  872. }
  873. }
  874. }
  875. void IPCPlayerApp::HandleJSError(StringHash eventType, VariantMap& eventData)
  876. {
  877. if (brokerActive_)
  878. {
  879. if (ipc_.Null())
  880. return;
  881. String errName = eventData[JSError::P_ERRORNAME].GetString();
  882. String errStack = eventData[JSError::P_ERRORSTACK].GetString();
  883. String errMessage = eventData[JSError::P_ERRORMESSAGE].GetString();
  884. String errFilename = eventData[JSError::P_ERRORFILENAME].GetString();
  885. int errLineNumber = eventData[JSError::P_ERRORLINENUMBER].GetInt();
  886. VariantMap ipcErrorData;
  887. ipcErrorData[IPCJSError::P_ERRORNAME] = errName;
  888. ipcErrorData[IPCJSError::P_ERRORSTACK] = errStack;
  889. ipcErrorData[IPCJSError::P_ERRORMESSAGE] = errMessage;
  890. ipcErrorData[IPCJSError::P_ERRORFILENAME] = errFilename;
  891. ipcErrorData[IPCJSError::P_ERRORLINENUMBER] = errLineNumber;
  892. ipc_->SendEventToBroker(E_IPCJSERROR, ipcErrorData);
  893. ATOMIC_LOGERROR("SENDING E_IPCJSERROR");
  894. }
  895. }
  896. void IPCPlayerApp::HandlePlayerWindowChanged(StringHash eventType, VariantMap& eventData)
  897. {
  898. Graphics* graphics = GetSubsystem<Graphics>();
  899. using namespace IPCPlayerWindowChanged;
  900. VariantMap data;
  901. data[P_POSX] = graphics->GetWindowPosition().x_;
  902. data[P_POSY] = graphics->GetWindowPosition().y_;
  903. data[P_WIDTH] = graphics->GetWidth();
  904. data[P_HEIGHT] = graphics->GetHeight();
  905. data[P_MONITOR] = graphics->GetCurrentMonitor();
  906. data[P_MAXIMIZED] = graphics->GetMaximized();
  907. ipc_->SendEventToBroker(E_IPCPLAYERWINDOWCHANGED, data);
  908. }
  909. void IPCPlayerApp::HandleUpdatesPausedResumed(StringHash eventType, VariantMap& eventData)
  910. {
  911. ipc_->SendEventToBroker(E_IPCPLAYERUPDATESPAUSEDRESUMED, eventData);
  912. }
  913. void IPCPlayerApp::HandleExitRequest(StringHash eventType, VariantMap& eventData)
  914. {
  915. // we are exiting, so let's clear out the debugger object
  916. arobj = NULL;
  917. UnsubscribeFromEvent(E_LOGMESSAGE);
  918. SendEvent(E_PLAYERQUIT);
  919. }
  920. void IPCPlayerApp::HandleLogMessage(StringHash eventType, VariantMap& eventData)
  921. {
  922. using namespace LogMessage;
  923. if (brokerActive_)
  924. {
  925. if (ipc_.Null())
  926. return;
  927. VariantMap logEvent;
  928. logEvent[IPCWorkerLog::P_LEVEL] = eventData[P_LEVEL].GetInt();
  929. logEvent[IPCWorkerLog::P_MESSAGE] = eventData[P_MESSAGE].GetString();
  930. ipc_->SendEventToBroker(E_IPCWORKERLOG, logEvent);
  931. }
  932. }
  933. }