IPCPlayerApp.cpp 33 KB

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