webruby 0.2.2 → 0.2.4

Sign up to get free protection for your applications and to get access to all the features.
Files changed (245) hide show
  1. checksums.yaml +4 -4
  2. data/lib/webruby/config.rb +4 -9
  3. data/lib/webruby/rake/files.rake +2 -2
  4. data/modules/emscripten/AUTHORS +9 -1
  5. data/modules/emscripten/CONTRIBUTING.markdown +5 -0
  6. data/modules/emscripten/ChangeLog +435 -0
  7. data/modules/emscripten/cmake/Modules/FindOpenAL.cmake +26 -0
  8. data/modules/emscripten/cmake/Platform/Emscripten.cmake +9 -2
  9. data/modules/emscripten/em++ +0 -2
  10. data/modules/emscripten/emcc +92 -32
  11. data/modules/emscripten/emlink.py +16 -13
  12. data/modules/emscripten/emmake +1 -1
  13. data/modules/emscripten/emrun +918 -0
  14. data/modules/emscripten/emrun.bat +2 -0
  15. data/modules/emscripten/emscripten.py +545 -20
  16. data/modules/emscripten/src/analyzer.js +6 -1
  17. data/modules/emscripten/src/compiler.js +25 -16
  18. data/modules/emscripten/src/emrun_postjs.js +20 -0
  19. data/modules/emscripten/{tests → src}/hello_world.js +0 -0
  20. data/modules/emscripten/src/intertyper.js +45 -16
  21. data/modules/emscripten/src/jsifier.js +78 -48
  22. data/modules/emscripten/src/library.js +381 -96
  23. data/modules/emscripten/src/library_browser.js +50 -53
  24. data/modules/emscripten/src/library_egl.js +66 -24
  25. data/modules/emscripten/src/library_fs.js +122 -90
  26. data/modules/emscripten/src/library_gl.js +739 -353
  27. data/modules/emscripten/src/library_glfw.js +9 -3
  28. data/modules/emscripten/src/library_glut.js +10 -5
  29. data/modules/emscripten/src/library_idbfs.js +14 -14
  30. data/modules/emscripten/src/library_memfs.js +65 -41
  31. data/modules/emscripten/src/library_nodefs.js +61 -9
  32. data/modules/emscripten/src/library_openal.js +4 -4
  33. data/modules/emscripten/src/library_path.js +9 -13
  34. data/modules/emscripten/src/library_sdl.js +301 -64
  35. data/modules/emscripten/src/library_sockfs.js +7 -5
  36. data/modules/emscripten/src/modules.js +62 -22
  37. data/modules/emscripten/src/parseTools.js +135 -102
  38. data/modules/emscripten/src/postamble.js +3 -4
  39. data/modules/emscripten/src/preamble.js +49 -29
  40. data/modules/emscripten/src/proxyClient.js +1 -1
  41. data/modules/emscripten/src/proxyWorker.js +10 -10
  42. data/modules/emscripten/src/relooper/Relooper.cpp +15 -4
  43. data/modules/emscripten/src/runtime.js +32 -8
  44. data/modules/emscripten/src/settings.js +25 -8
  45. data/modules/emscripten/src/shell.html +6 -3
  46. data/modules/emscripten/src/shell.js +13 -11
  47. data/modules/emscripten/src/simd.js +602 -432
  48. data/modules/emscripten/src/struct_info.json +22 -2
  49. data/modules/emscripten/src/utility.js +32 -17
  50. data/modules/emscripten/system/include/SDL/SDL_events.h +1 -0
  51. data/modules/emscripten/system/include/compat/ctype.h +17 -0
  52. data/modules/emscripten/system/include/compat/wchar.h +23 -0
  53. data/modules/emscripten/system/include/compat/wctype.h +23 -0
  54. data/modules/emscripten/system/include/emscripten/emmintrin.h +87 -0
  55. data/modules/emscripten/system/include/emscripten/emscripten.h +30 -4
  56. data/modules/emscripten/system/include/emscripten/vector.h +29 -1
  57. data/modules/emscripten/system/include/emscripten/xmmintrin.h +131 -0
  58. data/modules/emscripten/system/include/libcxx/CREDITS.TXT +9 -1
  59. data/modules/emscripten/system/include/libcxx/__bit_reference +8 -8
  60. data/modules/emscripten/system/include/libcxx/__config +95 -17
  61. data/modules/emscripten/system/include/libcxx/__debug +25 -4
  62. data/modules/emscripten/system/include/libcxx/__functional_03 +7 -7
  63. data/modules/emscripten/system/include/libcxx/__functional_base +169 -9
  64. data/modules/emscripten/system/include/libcxx/__functional_base_03 +1 -1
  65. data/modules/emscripten/system/include/libcxx/__hash_table +25 -25
  66. data/modules/emscripten/system/include/libcxx/__locale +21 -19
  67. data/modules/emscripten/system/include/libcxx/__mutex_base +2 -33
  68. data/modules/emscripten/system/include/libcxx/__split_buffer +9 -9
  69. data/modules/emscripten/system/include/libcxx/__std_stream +14 -0
  70. data/modules/emscripten/system/include/libcxx/__tree +35 -26
  71. data/modules/emscripten/system/include/libcxx/__tuple +15 -15
  72. data/modules/emscripten/system/include/libcxx/__tuple_03 +2 -2
  73. data/modules/emscripten/system/include/libcxx/__undef_min_max +8 -0
  74. data/modules/emscripten/system/include/libcxx/algorithm +121 -110
  75. data/modules/emscripten/system/include/libcxx/array +15 -15
  76. data/modules/emscripten/system/include/libcxx/bitset +4 -4
  77. data/modules/emscripten/system/include/libcxx/chrono +51 -17
  78. data/modules/emscripten/system/include/libcxx/cmath +25 -23
  79. data/modules/emscripten/system/include/libcxx/codecvt +21 -18
  80. data/modules/emscripten/system/include/libcxx/complex +48 -7
  81. data/modules/emscripten/system/include/libcxx/cstddef +1 -1
  82. data/modules/emscripten/system/include/libcxx/cstdio +8 -1
  83. data/modules/emscripten/system/include/libcxx/cstdlib +1 -1
  84. data/modules/emscripten/system/include/libcxx/cwchar +1 -1
  85. data/modules/emscripten/system/include/libcxx/deque +26 -12
  86. data/modules/emscripten/system/include/libcxx/dynarray +311 -0
  87. data/modules/emscripten/system/include/libcxx/exception +4 -4
  88. data/modules/emscripten/system/include/libcxx/ext/__hash +3 -3
  89. data/modules/emscripten/system/include/libcxx/ext/hash_map +19 -15
  90. data/modules/emscripten/system/include/libcxx/ext/hash_set +7 -3
  91. data/modules/emscripten/system/include/libcxx/forward_list +33 -7
  92. data/modules/emscripten/system/include/libcxx/fstream +4 -4
  93. data/modules/emscripten/system/include/libcxx/functional +200 -170
  94. data/modules/emscripten/system/include/libcxx/future +83 -39
  95. data/modules/emscripten/system/include/libcxx/initializer_list +24 -11
  96. data/modules/emscripten/system/include/libcxx/iomanip +147 -0
  97. data/modules/emscripten/system/include/libcxx/ios +24 -16
  98. data/modules/emscripten/system/include/libcxx/iosfwd +19 -19
  99. data/modules/emscripten/system/include/libcxx/istream +13 -8
  100. data/modules/emscripten/system/include/libcxx/iterator +108 -417
  101. data/modules/emscripten/system/include/libcxx/limits +8 -4
  102. data/modules/emscripten/system/include/libcxx/list +28 -8
  103. data/modules/emscripten/system/include/libcxx/locale +153 -390
  104. data/modules/emscripten/system/include/libcxx/map +280 -100
  105. data/modules/emscripten/system/include/libcxx/memory +49 -97
  106. data/modules/emscripten/system/include/libcxx/mutex +2 -2
  107. data/modules/emscripten/system/include/libcxx/new +43 -14
  108. data/modules/emscripten/system/include/libcxx/numeric +2 -2
  109. data/modules/emscripten/system/include/libcxx/optional +697 -0
  110. data/modules/emscripten/system/include/libcxx/ostream +17 -8
  111. data/modules/emscripten/system/include/libcxx/queue +5 -5
  112. data/modules/emscripten/system/include/libcxx/random +53 -51
  113. data/modules/emscripten/system/include/libcxx/ratio +11 -11
  114. data/modules/emscripten/system/include/libcxx/readme.txt +1 -1
  115. data/modules/emscripten/system/include/libcxx/regex +23 -20
  116. data/modules/emscripten/system/include/libcxx/scoped_allocator +1 -1
  117. data/modules/emscripten/system/include/libcxx/set +166 -2
  118. data/modules/emscripten/system/include/libcxx/shared_mutex +419 -0
  119. data/modules/emscripten/system/include/libcxx/sstream +4 -4
  120. data/modules/emscripten/system/include/libcxx/stack +3 -3
  121. data/modules/emscripten/system/include/libcxx/streambuf +5 -5
  122. data/modules/emscripten/system/include/libcxx/string +372 -324
  123. data/modules/emscripten/system/include/libcxx/support/ibm/limits.h +99 -0
  124. data/modules/emscripten/system/include/libcxx/support/ibm/support.h +54 -0
  125. data/modules/emscripten/system/include/libcxx/support/ibm/xlocale.h +326 -0
  126. data/modules/emscripten/system/include/libcxx/support/win32/limits_win32.h +6 -6
  127. data/modules/emscripten/system/include/libcxx/support/win32/locale_win32.h +15 -15
  128. data/modules/emscripten/system/include/libcxx/support/win32/math_win32.h +2 -0
  129. data/modules/emscripten/system/include/libcxx/support/win32/support.h +6 -1
  130. data/modules/emscripten/system/include/libcxx/system_error +14 -8
  131. data/modules/emscripten/system/include/libcxx/thread +7 -8
  132. data/modules/emscripten/system/include/libcxx/tuple +29 -88
  133. data/modules/emscripten/system/include/libcxx/type_traits +253 -209
  134. data/modules/emscripten/system/include/libcxx/typeindex +3 -3
  135. data/modules/emscripten/system/include/libcxx/unordered_map +162 -101
  136. data/modules/emscripten/system/include/libcxx/unordered_set +79 -2
  137. data/modules/emscripten/system/include/libcxx/utility +20 -20
  138. data/modules/emscripten/system/include/libcxx/valarray +23 -23
  139. data/modules/emscripten/system/include/libcxx/vector +114 -91
  140. data/modules/emscripten/system/lib/libc/musl/src/regex/regcomp.c +3352 -0
  141. data/modules/emscripten/system/lib/libc/musl/src/regex/regerror.c +35 -0
  142. data/modules/emscripten/system/lib/libc/musl/src/regex/regexec.c +1011 -0
  143. data/modules/emscripten/system/lib/libc/musl/src/regex/tre-mem.c +158 -0
  144. data/modules/emscripten/system/lib/libc/musl/src/regex/tre.h +231 -0
  145. data/modules/emscripten/system/lib/libcextra.symbols +7 -0
  146. data/modules/emscripten/system/lib/libcxx/CREDITS.TXT +9 -1
  147. data/modules/emscripten/system/lib/libcxx/algorithm.cpp +1 -0
  148. data/modules/emscripten/system/lib/libcxx/debug.cpp +66 -42
  149. data/modules/emscripten/system/lib/libcxx/exception.cpp +88 -16
  150. data/modules/emscripten/system/lib/libcxx/future.cpp +6 -0
  151. data/modules/emscripten/system/lib/libcxx/ios.cpp +7 -2
  152. data/modules/emscripten/system/lib/libcxx/iostream.cpp +8 -8
  153. data/modules/emscripten/system/lib/libcxx/locale.cpp +38 -11
  154. data/modules/emscripten/system/lib/libcxx/mutex.cpp +3 -0
  155. data/modules/emscripten/system/lib/libcxx/new.cpp +44 -10
  156. data/modules/emscripten/system/lib/libcxx/optional.cpp +25 -0
  157. data/modules/emscripten/system/lib/libcxx/random.cpp +26 -0
  158. data/modules/emscripten/system/lib/libcxx/readme.txt +1 -1
  159. data/modules/emscripten/system/lib/libcxx/shared_mutex.cpp +101 -0
  160. data/modules/emscripten/system/lib/libcxx/stdexcept.cpp +11 -7
  161. data/modules/emscripten/system/lib/libcxx/string.cpp +3 -1
  162. data/modules/emscripten/system/lib/libcxx/strstream.cpp +7 -7
  163. data/modules/emscripten/system/lib/libcxx/support/win32/locale_win32.cpp +12 -13
  164. data/modules/emscripten/system/lib/libcxx/support/win32/support.cpp +33 -36
  165. data/modules/emscripten/system/lib/libcxx/symbols +187 -168
  166. data/modules/emscripten/system/lib/libcxx/system_error.cpp +1 -0
  167. data/modules/emscripten/system/lib/libcxx/thread.cpp +7 -3
  168. data/modules/emscripten/system/lib/libcxx/typeinfo.cpp +9 -6
  169. data/modules/emscripten/system/lib/libcxx/valarray.cpp +2 -0
  170. data/modules/emscripten/third_party/lzma.js/doit.bat +4 -0
  171. data/modules/emscripten/third_party/lzma.js/doit.sh +9 -2
  172. data/modules/emscripten/tools/cache.py +5 -7
  173. data/modules/emscripten/tools/cache.pyc +0 -0
  174. data/modules/emscripten/tools/eliminator/asm-eliminator-test-output.js +7 -0
  175. data/modules/emscripten/tools/eliminator/asm-eliminator-test.js +9 -1
  176. data/modules/emscripten/tools/eliminator/eliminator-test-output.js +3 -0
  177. data/modules/emscripten/tools/eliminator/eliminator-test.js +9 -1
  178. data/modules/emscripten/tools/file_packager.py +93 -50
  179. data/modules/emscripten/tools/js-optimizer.js +98 -48
  180. data/modules/emscripten/tools/js_optimizer.py +4 -4
  181. data/modules/emscripten/tools/js_optimizer.pyc +0 -0
  182. data/modules/emscripten/tools/jsrun.py +1 -1
  183. data/modules/emscripten/tools/jsrun.pyc +0 -0
  184. data/modules/emscripten/tools/response_file.py +6 -0
  185. data/modules/emscripten/tools/response_file.pyc +0 -0
  186. data/modules/emscripten/tools/settings_template_readonly.py +2 -0
  187. data/modules/emscripten/tools/shared.py +88 -34
  188. data/modules/emscripten/tools/shared.pyc +0 -0
  189. data/modules/emscripten/tools/split.py +21 -13
  190. data/modules/mruby/build_config.rb +7 -1
  191. data/modules/mruby/doc/compile/README.md +5 -9
  192. data/modules/mruby/include/mrbconf.h +5 -2
  193. data/modules/mruby/include/mruby/array.h +1 -0
  194. data/modules/mruby/include/mruby/compile.h +2 -4
  195. data/modules/mruby/include/mruby/dump.h +7 -16
  196. data/modules/mruby/include/mruby/hash.h +1 -1
  197. data/modules/mruby/include/mruby/irep.h +14 -2
  198. data/modules/mruby/include/mruby/khash.h +8 -7
  199. data/modules/mruby/include/mruby/string.h +1 -0
  200. data/modules/mruby/include/mruby/value.h +5 -2
  201. data/modules/mruby/include/mruby.h +12 -13
  202. data/modules/mruby/mrbgems/mruby-bin-mirb/tools/mirb/mirb.c +16 -6
  203. data/modules/mruby/mrbgems/mruby-bin-mruby/tools/mruby/mruby.c +18 -30
  204. data/modules/mruby/mrbgems/mruby-fiber/src/fiber.c +21 -0
  205. data/modules/mruby/mrbgems/mruby-math/src/math.c +1 -1
  206. data/modules/mruby/mrbgems/mruby-random/src/random.c +144 -47
  207. data/modules/mruby/mrbgems/mruby-random/test/random.rb +44 -0
  208. data/modules/mruby/mrbgems/mruby-struct/src/struct.c +5 -5
  209. data/modules/mruby/mrblib/numeric.rb +99 -33
  210. data/modules/mruby/src/array.c +11 -4
  211. data/modules/mruby/src/backtrace.c +2 -2
  212. data/modules/mruby/src/class.c +49 -30
  213. data/modules/mruby/src/codegen.c +131 -79
  214. data/modules/mruby/src/debug.c +1 -1
  215. data/modules/mruby/src/dump.c +213 -163
  216. data/modules/mruby/src/error.c +17 -17
  217. data/modules/mruby/src/error.h +1 -1
  218. data/modules/mruby/src/etc.c +10 -0
  219. data/modules/mruby/src/gc.c +35 -17
  220. data/modules/mruby/src/hash.c +5 -5
  221. data/modules/mruby/src/kernel.c +36 -14
  222. data/modules/mruby/src/load.c +238 -296
  223. data/modules/mruby/src/numeric.c +18 -98
  224. data/modules/mruby/src/object.c +3 -5
  225. data/modules/mruby/src/parse.y +63 -56
  226. data/modules/mruby/src/proc.c +8 -5
  227. data/modules/mruby/src/re.h +0 -1
  228. data/modules/mruby/src/state.c +65 -27
  229. data/modules/mruby/src/string.c +3 -31
  230. data/modules/mruby/src/symbol.c +3 -3
  231. data/modules/mruby/src/variable.c +12 -5
  232. data/modules/mruby/src/vm.c +90 -72
  233. data/modules/mruby/tasks/mruby_build.rake +10 -1
  234. data/modules/mruby/tasks/toolchains/gcc.rake +12 -2
  235. data/modules/mruby/tasks/toolchains/{vs2012.rake → visualcpp.rake} +1 -1
  236. data/modules/mruby/test/driver.c +3 -3
  237. data/modules/mruby/test/t/array.rb +5 -5
  238. data/modules/mruby/test/t/class.rb +14 -1
  239. data/modules/mruby/test/t/kernel.rb +4 -0
  240. data/modules/mruby/test/t/module.rb +4 -4
  241. data/modules/mruby/test/t/nameerror.rb +1 -1
  242. data/modules/mruby/tools/mrbc/mrbc.c +23 -17
  243. data/modules/mruby/travis_config.rb +10 -1
  244. metadata +28 -5
  245. data/modules/mruby/tasks/toolchains/vs2010.rake +0 -3
@@ -0,0 +1,918 @@
1
+ #!/usr/bin/env python
2
+
3
+ # emrun: Implements machinery that allows running a .html page as if it was a standard executable file.
4
+ # Usage: emrun <options> filename.html <args to program>
5
+ # See emrun --help for more information
6
+
7
+ import os, platform, optparse, logging, re, pprint, atexit, urlparse, subprocess, sys, SocketServer, BaseHTTPServer, SimpleHTTPServer, time, string, struct, socket, cgi
8
+ from operator import itemgetter
9
+ from urllib import unquote
10
+ from Queue import PriorityQueue
11
+
12
+ # Populated from cmdline params
13
+ emrun_options = None
14
+
15
+ # Represents the process object handle to the browser we opened to run the html page.
16
+ browser_process = None
17
+
18
+ # If we have routed browser output to file with --log_stdout and/or --log_stderr,
19
+ # these track the handles.
20
+ browser_stdout_handle = sys.stdout
21
+ browser_stderr_handle = sys.stderr
22
+
23
+ # This flag tracks whether the html page has sent any stdout messages back to us.
24
+ # Used to detect whether we might have gotten detached from the browser process we
25
+ # spawned, in which case we are not able to detect when user closes the browser with
26
+ # the close button.
27
+ have_received_messages = False
28
+
29
+ # At startup print a warning message once if user did not build with --emrun.
30
+ emrun_not_enabled_nag_printed = False
31
+
32
+ # Stores the exit() code of the html page when/if it quits.
33
+ page_exit_code = 0
34
+
35
+ # If this is set to a non-empty string, all processes by this name will be killed at exit.
36
+ # This is used to clean up after browsers that spawn subprocesses to handle the actual
37
+ # browser launch. For example opera has a launcher.exe that runs the actual opera browser.
38
+ # So killing browser_process would just kill launcher.exe and not the opera browser itself.
39
+ processname_killed_atexit = ""
40
+
41
+ # If user does not specify a --port parameter, this port is used to launch the server.
42
+ default_webserver_port = 6931
43
+
44
+ # Host OS detection to autolocate browsers and other OS-specific support needs.
45
+ WINDOWS = False
46
+ LINUX = False
47
+ OSX = False
48
+ if os.name == 'nt':
49
+ WINDOWS = True
50
+
51
+ import win32api, _winreg
52
+ from win32com.client import GetObject
53
+ from win32api import GetFileVersionInfo, LOWORD, HIWORD
54
+ import shlex
55
+ from _winreg import HKEY_CURRENT_USER, OpenKey, QueryValue
56
+
57
+ elif platform.system() == 'Linux':
58
+ LINUX = True
59
+ elif platform.mac_ver()[0] != '':
60
+ OSX = True
61
+
62
+ import plistlib
63
+
64
+ # If you are running on an OS that is not any of these, must add explicit support for it.
65
+ if not WINDOWS and not LINUX and not OSX:
66
+ raise Exception("Unknown OS!")
67
+
68
+ # Absolute wallclock time in seconds specifying when the previous HTTP stdout message from
69
+ # the page was received.
70
+ last_message_time = time.clock()
71
+
72
+ # Absolute wallclock time in seconds telling when we launched emrun.
73
+ page_start_time = time.clock()
74
+
75
+ # Stores the time of most recent http page serve.
76
+ page_last_served_time = time.clock()
77
+
78
+ # Returns given log message formatted to be outputted on a HTML page.
79
+ def format_html(msg):
80
+ if not msg.endswith('\n'):
81
+ msg += '\n'
82
+ msg = cgi.escape(msg)
83
+ msg = msg.replace('\r\n', '<br />').replace('\n', '<br />')
84
+ return msg
85
+
86
+ # Prints a log message to 'info' stdout channel. Always printed.
87
+ def logi(msg):
88
+ global last_message_time
89
+ if emrun_options.log_html:
90
+ sys.stdout.write(format_html(msg))
91
+ else:
92
+ print >> sys.stdout, msg
93
+ sys.stdout.flush()
94
+ last_message_time = time.clock()
95
+
96
+ # Prints a verbose log message to stdout channel. Only shown if run with --verbose.
97
+ def logv(msg):
98
+ global emrun_options, last_message_time
99
+ if emrun_options.verbose:
100
+ if emrun_options.log_html:
101
+ sys.stdout.write(format_html(msg))
102
+ else:
103
+ print >> sys.stdout, msg
104
+ sys.stdout.flush()
105
+ last_message_time = time.clock()
106
+
107
+ # Prints an error message to stderr channel.
108
+ def loge(msg):
109
+ global last_message_time
110
+ if emrun_options.log_html:
111
+ sys.stderr.write(format_html(msg))
112
+ else:
113
+ print >> sys.stderr, msg
114
+ sys.stderr.flush()
115
+ last_message_time = time.clock()
116
+
117
+ def format_eol(msg):
118
+ if WINDOWS:
119
+ msg = msg.replace('\r\n', '\n').replace('\n', '\r\n')
120
+ return msg
121
+
122
+ # Prints a message to the browser stdout output stream.
123
+ def browser_logi(msg):
124
+ global browser_stdout_handle
125
+ if browser_stdout_handle != sys.stdout and not msg.endswith('\n'):
126
+ msg += '\n'
127
+ msg = format_eol(msg)
128
+ print >> browser_stdout_handle, msg
129
+ browser_stdout_handle.flush()
130
+ last_message_time = time.clock()
131
+
132
+ # Prints a message to the browser stderr output stream.
133
+ def browser_loge(msg):
134
+ global browser_stderr_handle
135
+ if browser_stderr_handle != sys.stderr and not msg.endswith('\n'):
136
+ msg += '\n'
137
+ msg = format_eol(msg)
138
+ print >> browser_stderr_handle, msg
139
+ browser_stderr_handle.flush()
140
+ last_message_time = time.clock()
141
+
142
+ # Unquotes a unicode string. (translates ascii-encoded utf string back to utf)
143
+ def unquote_u(source):
144
+ result = unquote(source)
145
+ if '%u' in result:
146
+ result = result.replace('%u','\\u').decode('unicode_escape')
147
+ return result
148
+
149
+ # Returns whether the browser page we spawned is still running.
150
+ # (note, not perfect atm, in case we are running in detached mode)
151
+ def is_browser_process_alive():
152
+ return browser_process and browser_process.poll() == None
153
+
154
+ # Kills browser_process and processname_killed_atexit.
155
+ def kill_browser_process():
156
+ global browser_process, processname_killed_atexit
157
+ if browser_process:
158
+ try:
159
+ logv('Terminating browser process..')
160
+ browser_process.kill()
161
+ except:
162
+ pass
163
+ browser_process = None
164
+
165
+ if len(processname_killed_atexit) > 0:
166
+ logv("Terminating all processes that have string '" + processname_killed_atexit + "' in their name.")
167
+ if WINDOWS:
168
+ process_image = processname_killed_atexit if '.exe' in processname_killed_atexit else (processname_killed_atexit + '.exe')
169
+ process = subprocess.Popen(['taskkill', '/F', '/IM', process_image, '/T'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
170
+ process.communicate()
171
+ else:
172
+ try:
173
+ subprocess.call(['pkill', processname_killed_atexit])
174
+ except OSError, e:
175
+ try:
176
+ subprocess.call(['killall', processname_killed_atexit])
177
+ except OSError, e:
178
+ loge('Both commands pkill and killall failed to clean up the spawned browser process. Perhaps neither of these utilities is available on your system?')
179
+ processname_killed_atexit = ''
180
+
181
+ # Our custom HTTP web server that will server the target page to run via .html.
182
+ # This is used so that we can load the page via a http:// URL instead of a file:// URL, since those wouldn't work too well unless user allowed XHR without CORS rules.
183
+ # Also, the target page will route its stdout and stderr back to here via HTTP requests.
184
+ class HTTPWebServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
185
+ # Log messaging arriving via HTTP can come in out of sequence. Implement a sequencing mechanism to enforce ordered transmission.
186
+ expected_http_seq_num = -1
187
+ # Stores messages that have arrived out of order, pending for a send as soon as the missing message arrives.
188
+ # Kept in sorted order, first element is the oldest message received.
189
+ http_message_queue = []
190
+
191
+ def handle_incoming_message(self, seq_num, log, data):
192
+ global have_received_messages
193
+ have_received_messages = True
194
+
195
+ if self.expected_http_seq_num == -1:
196
+ self.expected_http_seq_num = seq_num+1
197
+ log(data)
198
+ elif seq_num == -1: # Message arrived without a sequence number? Just log immediately
199
+ log(data)
200
+ elif seq_num == self.expected_http_seq_num:
201
+ log(data)
202
+ self.expected_http_seq_num += 1
203
+ self.print_messages_due()
204
+ elif seq_num < self.expected_http_seq_num:
205
+ log(data)
206
+ else:
207
+ log(data)
208
+ self.http_message_queue += [(seq_num, data, log)]
209
+ self.http_message_queue.sort(key=itemgetter(0))
210
+ if len(self.http_message_queue) > 16:
211
+ self.print_next_message()
212
+
213
+ # If it's been too long since we we got a message, prints out the oldest queued message, ignoring the proper order.
214
+ # This ensures that if any messages are actually lost, that the message queue will be orderly flushed.
215
+ def print_timed_out_messages(self):
216
+ global last_message_time
217
+ now = time.clock()
218
+ max_message_queue_time = 5
219
+ if len(self.http_message_queue) > 0 and now - last_message_time > max_message_queue_time:
220
+ self.print_next_message()
221
+
222
+ # Skips to printing the next message in queue now, independent of whether there was missed messages in the sequence numbering.
223
+ def print_next_message(self):
224
+ if len(self.http_message_queue) > 0:
225
+ self.expected_http_seq_num = self.http_message_queue[0][0]
226
+ self.print_messages_due()
227
+
228
+ # Completely flushes all out-of-order messages in the queue.
229
+ def print_all_messages(self):
230
+ while len(self.http_message_queue) > 0:
231
+ self.print_next_message()
232
+
233
+ # Prints any messages that are now due after we logged some other previous messages.
234
+ def print_messages_due(self):
235
+ while len(self.http_message_queue) > 0:
236
+ msg = self.http_message_queue[0]
237
+ if msg[0] == self.expected_http_seq_num:
238
+ msg[2](msg[1])
239
+ self.expected_http_seq_num += 1
240
+ self.http_message_queue.pop(0)
241
+ else:
242
+ return
243
+
244
+ def serve_forever(self, timeout=0.5):
245
+ global emrun_options, last_message_time, page_exit_code, have_received_messages, emrun_not_enabled_nag_printed
246
+ self.is_running = True
247
+ self.timeout = timeout
248
+ while self.is_running:
249
+ now = time.clock()
250
+ # Did user close browser?
251
+ if not emrun_options.serve_after_close and browser_process and browser_process.poll() != None:
252
+ if not have_received_messages:
253
+ emrun_options.serve_after_close = True
254
+ logv('Warning: emrun got detached from the target browser process. Cannot detect when user closes the browser. Behaving as if --serve_after_close was passed in.')
255
+ else:
256
+ self.shutdown()
257
+ logv('Browser process has quit. Shutting down web server.. Pass --serve_after_close to keep serving the page even after the browser closes.')
258
+
259
+ # Serve HTTP
260
+ self.handle_request()
261
+ # Process message log queue
262
+ self.print_timed_out_messages()
263
+
264
+ # If web page was silent for too long without printing anything, kill process.
265
+ time_since_message = now - last_message_time
266
+ if emrun_options.silence_timeout != 0 and time_since_message > emrun_options.silence_timeout:
267
+ self.shutdown()
268
+ logv('No activity in ' + str(emrun_options.silence_timeout) + ' seconds. Quitting web server with return code ' + str(emrun_options.timeout_returncode) + '. (--silence_timeout option)')
269
+ page_exit_code = emrun_options.timeout_returncode
270
+ emrun_options.kill_on_exit = True
271
+
272
+ # If the page has been running too long as a whole, kill process.
273
+ time_since_start = now - page_start_time
274
+ if emrun_options.timeout != 0 and time_since_start > emrun_options.timeout:
275
+ self.shutdown()
276
+ logv('Page has not finished in ' + str(emrun_options.timeout) + ' seconds. Quitting web server with return code ' + str(emrun_options.timeout_returncode) + '. (--timeout option)')
277
+ emrun_options.kill_on_exit = True
278
+ page_exit_code = emrun_options.timeout_returncode
279
+
280
+ # If we detect that the page is not running with emrun enabled, print a warning message.
281
+ time_since_page_serve = now - page_last_served_time
282
+ if not emrun_not_enabled_nag_printed and not have_received_messages and time_since_page_serve > 5:
283
+ logi('The html page you are running is not emrun-capable. Stdout, stderr and exit(returncode) capture will not work. Recompile the application with the --emrun linker flag to enable this, or pass --no_emrun_detect to emrun to hide this check.')
284
+ emrun_not_enabled_nag_printed = True
285
+
286
+ # Clean up at quit, print any leftover messages in queue.
287
+ self.print_all_messages()
288
+
289
+ def handle_error(self, request, client_address):
290
+ err = sys.exc_info()[1][0]
291
+ # Filter out the useless '[Errno 10054] An existing connection was forcibly closed by the remote host' errors that occur when we
292
+ # forcibly kill the client.
293
+ if err != 10054:
294
+ SocketServer.BaseServer.handle_error(self, request, client_address)
295
+
296
+ def shutdown(self):
297
+ self.is_running = False
298
+ self.print_all_messages()
299
+ return 1
300
+
301
+ # Processes HTTP request back to the browser.
302
+ class HTTPHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
303
+ def send_head(self):
304
+ global page_last_served_time
305
+ path = self.translate_path(self.path)
306
+ f = None
307
+
308
+ if os.path.isdir(path):
309
+ if not self.path.endswith('/'):
310
+ self.send_response(301)
311
+ self.send_header("Location", self.path + "/")
312
+ self.end_headers()
313
+ return None
314
+ for index in "index.html", "index.htm":
315
+ index = os.path.join(path, index)
316
+ if os.path.isfile(index):
317
+ path = index
318
+ break
319
+ else:
320
+ # Manually implement directory listing support.
321
+ return self.list_directory(path)
322
+ ctype = self.guess_type(path)
323
+ try:
324
+ f = open(path, 'rb')
325
+ except IOError:
326
+ self.send_error(404, "File not found: " + path)
327
+ return None
328
+ self.send_response(200)
329
+ self.send_header("Content-type", ctype)
330
+ fs = os.fstat(f.fileno())
331
+ self.send_header("Content-Length", str(fs[6]))
332
+ self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
333
+ self.send_header('Cache-Control','no-cache, must-revalidate')
334
+ self.send_header('Expires','-1')
335
+ self.end_headers()
336
+ page_last_served_time = time.clock()
337
+ return f
338
+
339
+ def log_request(self, code):
340
+ # Filter out 200 OK messages to remove noise.
341
+ if code is not 200:
342
+ SimpleHTTPServer.SimpleHTTPRequestHandler.log_request(self, code)
343
+
344
+ def log_message(self, format, *args):
345
+ msg = "%s - - [%s] %s\n" % (self.address_string(), self.log_date_time_string(), format%args)
346
+ if not 'favicon.ico' in msg: # Filter out 404 messages on favicon.ico not being found to remove noise.
347
+ sys.stderr.write(msg)
348
+
349
+ def do_POST(self):
350
+ global page_exit_code, emrun_options, have_received_messages
351
+
352
+ (_, _, path, query, _) = urlparse.urlsplit(self.path)
353
+ data = self.rfile.read(int(self.headers['Content-Length']))
354
+ data = data.replace("+", " ")
355
+ data = unquote_u(data)
356
+
357
+ # The user page sent a message with POST. Parse the message and log it to stdout/stderr.
358
+ is_stdout = False
359
+ is_stderr = False
360
+ seq_num = -1
361
+ # The html shell is expected to send messages of form ^out^(number)^(message) or ^err^(number)^(message).
362
+ if data.startswith('^err^'):
363
+ is_stderr = True
364
+ elif data.startswith('^out^'):
365
+ is_stdout = True
366
+ if is_stderr or is_stdout:
367
+ try:
368
+ i = data.index('^', 5)
369
+ seq_num = int(data[5:i])
370
+ data = data[i+1:]
371
+ except:
372
+ pass
373
+
374
+ is_exit = data.startswith('^exit^')
375
+
376
+ if data == '^pageload^': # Browser is just notifying that it has successfully launched the page.
377
+ have_received_messages = True
378
+ elif not is_exit:
379
+ log = browser_loge if is_stderr else browser_logi
380
+ self.server.handle_incoming_message(seq_num, log, data)
381
+ elif not emrun_options.serve_after_exit:
382
+ page_exit_code = int(data[6:])
383
+ logv('Web page has quit with a call to exit() with return code ' + str(page_exit_code) + '. Shutting down web server. Pass --serve_after_exit to keep serving even after the page terminates with exit().')
384
+ self.server.shutdown()
385
+
386
+ self.send_response(200)
387
+ self.send_header("Content-type", "text/plain")
388
+ self.send_header('Cache-Control','no-cache, must-revalidate')
389
+ self.send_header('Expires','-1')
390
+ self.end_headers()
391
+ self.wfile.write('OK')
392
+
393
+ # From http://stackoverflow.com/questions/4842448/getting-processor-information-in-python
394
+ # Returns a string with something like "AMD64, Intel(R) Core(TM) i5-2557M CPU @ 1.70GHz, Intel64 Family 6 Model 42 Stepping 7, GenuineIntel"
395
+ def get_cpu_infoline():
396
+ try:
397
+ if WINDOWS:
398
+ root_winmgmts = GetObject("winmgmts:root\cimv2")
399
+ cpus = root_winmgmts.ExecQuery("Select * from Win32_Processor")
400
+ cpu_name = cpus[0].Name + ', ' + platform.processor()
401
+ elif OSX:
402
+ cpu_name = subprocess.check_output(['sysctl', '-n', 'machdep.cpu.brand_string']).strip()
403
+ elif LINUX:
404
+ command = "cat /proc/cpuinfo"
405
+ all_info = subprocess.check_output(command, shell=True).strip()
406
+ for line in all_info.split("\n"):
407
+ if "model name" in line:
408
+ cpu_name = re.sub( ".*model name.*:", "", line,1).strip()
409
+ except:
410
+ return "Unknown"
411
+
412
+ return platform.machine() + ', ' + cpu_name
413
+
414
+ def win_print_gpu_info():
415
+ gpus = []
416
+ gpu_memory = []
417
+
418
+ for i in range(0, 16):
419
+ try:
420
+ hHardwareReg = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, "HARDWARE")
421
+ hDeviceMapReg = _winreg.OpenKey(hHardwareReg, "DEVICEMAP")
422
+ hVideoReg = _winreg.OpenKey(hDeviceMapReg, "VIDEO")
423
+ VideoCardString = _winreg.QueryValueEx(hVideoReg,"\Device\Video"+str(i))[0]
424
+ #Get Rid of Registry/Machine from the string
425
+ VideoCardStringSplit = VideoCardString.split("\\")
426
+ ClearnVideoCardString = string.join(VideoCardStringSplit[3:], "\\")
427
+ #Go up one level for detailed
428
+ VideoCardStringRoot = string.join(VideoCardStringSplit[3:len(VideoCardStringSplit)-1], "\\")
429
+
430
+ #Get the graphics card information
431
+ hVideoCardReg = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, ClearnVideoCardString)
432
+ try:
433
+ VideoCardDescription = _winreg.QueryValueEx(hVideoCardReg, "Device Description")[0]
434
+ except WindowsError:
435
+ VideoCardDescription = _winreg.QueryValueEx(hVideoCardReg, "DriverDesc")[0]
436
+
437
+ try:
438
+ driverVersion = _winreg.QueryValueEx(hVideoCardReg, "DriverVersion")[0]
439
+ VideoCardDescription += ', driver version ' + driverVersion
440
+ except:
441
+ pass
442
+
443
+ try:
444
+ driverDate = _winreg.QueryValueEx(hVideoCardReg, "DriverDate")[0]
445
+ VideoCardDescription += ' (' + driverDate + ')'
446
+ except:
447
+ pass
448
+
449
+ VideoCardMemorySize = _winreg.QueryValueEx(hVideoCardReg, "HardwareInformation.MemorySize")[0]
450
+ try:
451
+ vram = struct.unpack('l',VideoCardMemorySize)[0]
452
+ except struct.error:
453
+ vram = int(VideoCardMemorySize)
454
+ if not VideoCardDescription in gpus:
455
+ gpus += [VideoCardDescription]
456
+ gpu_memory += [str(int(vram/1024/1024))]
457
+ except WindowsError:
458
+ pass
459
+
460
+ if len(gpus) == 1:
461
+ print "GPU: " + gpus[0] + " with " + gpu_memory[0] + " MB of VRAM"
462
+ elif len(gpus) > 1:
463
+ for i in range(0, len(gpus)):
464
+ print "GPU"+str(i)+ ": " + gpus[i] + " with " + gpu_memory[i] + " MBs of VRAM"
465
+
466
+ def linux_print_gpu_info():
467
+ glxinfo = subprocess.check_output('glxinfo')
468
+ for line in glxinfo.split("\n"):
469
+ if "OpenGL vendor string:" in line:
470
+ gl_vendor = line[len("OpenGL vendor string:"):].strip()
471
+ if "OpenGL version string:" in line:
472
+ gl_version = line[len("OpenGL version string:"):].strip()
473
+ if "OpenGL renderer string:" in line:
474
+ gl_renderer = line[len("OpenGL renderer string:"):].strip()
475
+ logi('GPU: ' + gl_vendor + ' ' + gl_renderer + ', GL version ' + gl_version)
476
+
477
+ def osx_print_gpu_info():
478
+ try:
479
+ info = subprocess.check_output(['system_profiler', 'SPDisplaysDataType'])
480
+ gpu = re.search("Chipset Model: (.*)", info)
481
+ if gpu:
482
+ chipset = gpu.group(1)
483
+ vram = re.search("VRAM \(Total\): (.*) MB", info)
484
+ if vram:
485
+ logi('GPU: ' + chipset + ' with ' + vram.group(1) + ' MBs of VRAM')
486
+ else:
487
+ logi('GPU: ' + chipset)
488
+ except:
489
+ pass
490
+
491
+ def print_gpu_infolines():
492
+ if WINDOWS:
493
+ win_print_gpu_info()
494
+ elif LINUX:
495
+ linux_print_gpu_info()
496
+ elif OSX:
497
+ osx_print_gpu_info()
498
+
499
+ def get_executable_version(filename):
500
+ try:
501
+ if WINDOWS:
502
+ info = GetFileVersionInfo(filename, "\\")
503
+ ms = info['FileVersionMS']
504
+ ls = info['FileVersionLS']
505
+ version = HIWORD (ms), LOWORD (ms), HIWORD (ls), LOWORD (ls)
506
+ return '.'.join(map(str, version))
507
+ elif OSX:
508
+ plistfile = app_name[0:app_name.find('MacOS')] + 'Info.plist'
509
+ info = plistlib.readPlist(plistfile)
510
+ # Data in Info.plists is a bit odd, this check combo gives best information on each browser.
511
+ if 'firefox' in app_name.lower():
512
+ return info['CFBundleShortVersionString'] + ' 20' + info['CFBundleVersion'][2:].replace('.', '-')
513
+ if 'opera' in app_name.lower():
514
+ return info['CFBundleVersion']
515
+ else:
516
+ return info['CFBundleShortVersionString']
517
+ elif LINUX:
518
+ if 'firefox' in filename.lower():
519
+ version = subprocess.check_output([filename, '-v'])
520
+ version = version.replace('Mozilla Firefox ', '')
521
+ return version.strip()
522
+ else:
523
+ return ""
524
+ except:
525
+ return ""
526
+
527
+ # http://stackoverflow.com/questions/580924/python-windows-file-version-attribute
528
+ def win_get_file_properties(fname):
529
+ propNames = ('Comments', 'InternalName', 'ProductName',
530
+ 'CompanyName', 'LegalCopyright', 'ProductVersion',
531
+ 'FileDescription', 'LegalTrademarks', 'PrivateBuild',
532
+ 'FileVersion', 'OriginalFilename', 'SpecialBuild')
533
+
534
+ props = {'FixedFileInfo': None, 'StringFileInfo': None, 'FileVersion': None}
535
+
536
+ try:
537
+ # backslash as parm returns dictionary of numeric info corresponding to VS_FIXEDFILEINFO struc
538
+ fixedInfo = win32api.GetFileVersionInfo(fname, '\\')
539
+ props['FixedFileInfo'] = fixedInfo
540
+ props['FileVersion'] = "%d.%d.%d.%d" % (fixedInfo['FileVersionMS'] / 65536,
541
+ fixedInfo['FileVersionMS'] % 65536, fixedInfo['FileVersionLS'] / 65536,
542
+ fixedInfo['FileVersionLS'] % 65536)
543
+
544
+ # \VarFileInfo\Translation returns list of available (language, codepage)
545
+ # pairs that can be used to retreive string info. We are using only the first pair.
546
+ lang, codepage = win32api.GetFileVersionInfo(fname, '\\VarFileInfo\\Translation')[0]
547
+
548
+ # any other must be of the form \StringfileInfo\%04X%04X\parm_name, middle
549
+ # two are language/codepage pair returned from above
550
+
551
+ strInfo = {}
552
+ for propName in propNames:
553
+ strInfoPath = u'\\StringFileInfo\\%04X%04X\\%s' % (lang, codepage, propName)
554
+ ## print str_info
555
+ strInfo[propName] = win32api.GetFileVersionInfo(fname, strInfoPath)
556
+
557
+ props['StringFileInfo'] = strInfo
558
+ except:
559
+ pass
560
+
561
+ return props
562
+
563
+ def get_os_version():
564
+ try:
565
+ if WINDOWS:
566
+ versionHandle = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion")
567
+ productName = _winreg.QueryValueEx(versionHandle, "ProductName")
568
+ return productName[0]
569
+ elif OSX:
570
+ return 'Mac OS ' + platform.mac_ver()[0]
571
+ elif LINUX:
572
+ kernel_version = subprocess.check_output(['uname', '-r']).strip()
573
+ return ' '.join(platform.linux_distribution()) + ', linux kernel ' + kernel_version + ' ' + platform.architecture()[0]
574
+ except:
575
+ return 'Unknown OS'
576
+
577
+ def get_system_memory():
578
+ try:
579
+ if WINDOWS:
580
+ return win32api.GlobalMemoryStatusEx()['TotalPhys']
581
+ elif OSX:
582
+ return int(subprocess.check_output(['sysctl', '-n', 'hw.memsize']).strip())
583
+ elif LINUX:
584
+ mem = open('/proc/meminfo', 'r')
585
+ lines = mem.readlines()
586
+ mem.close()
587
+ for i in lines:
588
+ sline = i.split()
589
+ if str(sline[0]) == 'MemTotal:':
590
+ return int(sline[1]) * 1024
591
+ except:
592
+ return -1
593
+
594
+ # Finds the given executable 'program' in PATH. Operates like the Unix tool 'which'.
595
+ def which(program):
596
+ def is_exe(fpath):
597
+ return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
598
+
599
+ fpath, fname = os.path.split(program)
600
+ if fpath:
601
+ if is_exe(program):
602
+ return program
603
+ else:
604
+ for path in os.environ["PATH"].split(os.pathsep):
605
+ path = path.strip('"')
606
+ exe_file = os.path.join(path, program)
607
+ if is_exe(exe_file):
608
+ return exe_file
609
+
610
+ if WINDOWS and not '.' in fname:
611
+ if is_exe(exe_file + '.exe'):
612
+ return exe_file + '.exe'
613
+ if is_exe(exe_file + '.cmd'):
614
+ return exe_file + '.cmd'
615
+ if is_exe(exe_file + '.bat'):
616
+ return exe_file + '.bat'
617
+
618
+ return None
619
+
620
+ def win_get_default_browser():
621
+ # Manually find the default system browser on Windows without relying on 'start %1' since
622
+ # that method has an issue, see comment below.
623
+
624
+ # In Py3, this module is called winreg without the underscore
625
+
626
+ with OpenKey(HKEY_CURRENT_USER, r"Software\Classes\http\shell\open\command") as key:
627
+ cmd = QueryValue(key, None)
628
+ if cmd:
629
+ parts = shlex.split(cmd)
630
+ if len(parts) > 0:
631
+ return [parts[0]]
632
+
633
+ # Fall back to 'start %1', which we have to treat as if user passed --serve_forever, since
634
+ # for some reason, we are not able to detect when the browser closes when this is passed.
635
+ return ['cmd', '/C', 'start']
636
+
637
+ def find_browser(name):
638
+ if WINDOWS and name == 'start':
639
+ return win_get_default_browser()
640
+ if OSX and name == 'open':
641
+ return [name]
642
+
643
+ if os.path.isfile(os.path.abspath(name)):
644
+ return [name]
645
+ if os.path.isfile(os.path.abspath(name)+'.exe'):
646
+ return [os.path.abspath(name)+'.exe']
647
+ if os.path.isfile(os.path.abspath(name)+'.cmd'):
648
+ return [os.path.abspath(name)+'.cmd']
649
+ if os.path.isfile(os.path.abspath(name)+'.bat'):
650
+ return [os.path.abspath(name)+'.bat']
651
+
652
+ path_lookup = which(name)
653
+ if path_lookup != None:
654
+ return [path_lookup]
655
+
656
+ browser_locations = []
657
+ if OSX:
658
+ # Note: by default Firefox beta installs as 'Firefox.app', you must manually rename it to
659
+ # FirefoxBeta.app after installation.
660
+ browser_locations = [ ('firefox', '/Applications/Firefox.app/Contents/MacOS/firefox'),
661
+ ('firefox_beta', '/Applications/FirefoxBeta.app/Contents/MacOS/firefox'),
662
+ ('firefox_aurora', '/Applications/FirefoxAurora.app/Contents/MacOS/firefox'),
663
+ ('firefox_nightly', '/Applications/FirefoxNightly.app/Contents/MacOS/firefox'),
664
+ ('safari', '/Applications/Safari.app/Contents/MacOS/Safari'),
665
+ ('opera', '/Applications/Opera.app/Contents/MacOS/Opera'),
666
+ ('chrome', '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'),
667
+ ('chrome_canary', '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary') ]
668
+ elif WINDOWS:
669
+ pf_locations = ['ProgramFiles(x86)', 'ProgramFiles', 'ProgramW6432']
670
+
671
+ for pf_env in pf_locations:
672
+ if not pf_env in os.environ:
673
+ continue
674
+ program_files = os.environ[pf_env] if WINDOWS else ''
675
+
676
+ browser_locations += [ ('chrome', os.path.join(program_files, 'Google/Chrome/Application/chrome.exe')),
677
+ ('chrome_canary', os.path.expanduser("~/AppData/Local/Google/Chrome SxS/Application/chrome.exe")),
678
+ ('firefox_nightly', os.path.join(program_files, 'Nightly/firefox.exe')),
679
+ ('firefox_aurora', os.path.join(program_files, 'Aurora/firefox.exe')),
680
+ ('firefox_beta', os.path.join(program_files, 'Beta/firefox.exe')),
681
+ ('firefox_beta', os.path.join(program_files, 'FirefoxBeta/firefox.exe')),
682
+ ('firefox_beta', os.path.join(program_files, 'Firefox Beta/firefox.exe')),
683
+ ('firefox', os.path.join(program_files, 'Mozilla Firefox/firefox.exe')),
684
+ ('iexplore', os.path.join(program_files, 'Internet Explorer/iexplore.exe')),
685
+ ('opera', os.path.join(program_files, 'Opera/launcher.exe')) ]
686
+
687
+ elif LINUX:
688
+ browser_locations = [ ('firefox', os.path.expanduser('~/firefox/firefox')),
689
+ ('firefox_beta', os.path.expanduser('~/firefox_beta/firefox')),
690
+ ('firefox_aurora', os.path.expanduser('~/firefox_aurora/firefox')),
691
+ ('firefox_nightly', os.path.expanduser('~/firefox_nightly/firefox')),
692
+ ('chrome', which('google-chrome-stable'))]
693
+
694
+ for (alias, browser_exe) in browser_locations:
695
+ if name == alias:
696
+ if os.path.isfile(browser_exe):
697
+ return [browser_exe]
698
+
699
+ return None # Could not find the browser
700
+
701
+ def browser_display_name(browser):
702
+ b = browser.lower()
703
+ if 'iexplore' in b:
704
+ return 'Microsoft Internet Explorer'
705
+ if 'chrome' in b:
706
+ return 'Google Chrome'
707
+ if 'firefox' in b:
708
+ # Try to identify firefox flavor explicitly, to help show issues where emrun would launch the wrong browser.
709
+ product_name = win_get_file_properties(browser)['StringFileInfo']['ProductName'] if WINDOWS else 'firefox'
710
+ if product_name.lower() != 'firefox':
711
+ return 'Mozilla Firefox ' + product_name
712
+ else:
713
+ return 'Mozilla Firefox'
714
+ if 'opera' in b:
715
+ return 'Opera'
716
+ if 'safari' in b:
717
+ return 'Apple Safari'
718
+ return browser
719
+
720
+ def main():
721
+ global browser_process, processname_killed_atexit, emrun_options, emrun_not_enabled_nag_printed
722
+ usage_str = "usage: %prog [options] [optional_portnum]"
723
+ parser = optparse.OptionParser(usage=usage_str)
724
+
725
+ parser.add_option('--kill_start', dest='kill_on_start', action='store_true', default=False,
726
+ help='If true, any previously running instances of the target browser are killed before starting.')
727
+
728
+ parser.add_option('--kill_exit', dest='kill_on_exit', action='store_true', default=False,
729
+ help='If true, the spawned browser process is forcibly killed when it calls exit().')
730
+
731
+ parser.add_option('--no_server', dest='no_server', action='store_true', default=False,
732
+ help='If specified, a HTTP web server is not launched to host the page to run.')
733
+
734
+ parser.add_option('--no_browser', dest='no_browser', action='store_true', default=False,
735
+ help='If specified, emrun will not launch a web browser to run the page.')
736
+
737
+ parser.add_option('--no_emrun_detect', dest='no_emrun_detect', action='store_true', default=False,
738
+ help='If specified, skips printing the warning message if html page is detected to not have been built with --emrun linker flag.')
739
+
740
+ parser.add_option('--serve_after_close', dest='serve_after_close', action='store_true', default=False,
741
+ help='If true, serves the web page even after the application quits by user closing the web page.')
742
+
743
+ parser.add_option('--serve_after_exit', dest='serve_after_exit', action='store_true', default=False,
744
+ help='If true, serves the web page even after the application quits by a call to exit().')
745
+
746
+ parser.add_option('--serve_root', dest='serve_root', default='',
747
+ help='If set, specifies the root path that the emrun web server serves. If not specified, the directory where the target .html page lives in is served.')
748
+
749
+ parser.add_option('--verbose', dest='verbose', action='store_true', default=False,
750
+ help='Enable verbose logging from emrun internal operation.')
751
+
752
+ parser.add_option('--port', dest='port', default=default_webserver_port, type="int",
753
+ help='Specifies the port the server runs in.')
754
+
755
+ parser.add_option('--log_stdout', dest='log_stdout', default='',
756
+ help='Specifies a log filename where the browser process stdout data will be appended to.')
757
+
758
+ parser.add_option('--log_stderr', dest='log_stderr', default='',
759
+ help='Specifies a log filename where the browser process stderr data will be appended to.')
760
+
761
+ parser.add_option('--silence_timeout', dest='silence_timeout', type="int", default=0,
762
+ help='If no activity is received in this many seconds, the browser process is assumed to be hung, and the web server is shut down and the target browser killed. Disabled by default.')
763
+
764
+ parser.add_option('--timeout', dest='timeout', type="int", default=0,
765
+ help='If the browser process does not quit or the page exit() in this many seconds, the browser is assumed to be hung, and the web server is shut down and the target browser killed. Disabled by default.')
766
+
767
+ parser.add_option('--timeout_returncode', dest='timeout_returncode', type="int", default=99999,
768
+ help='Sets the exit code that emrun reports back to caller in the case that a page timeout occurs. Default: 99999.')
769
+
770
+ parser.add_option('--list_browsers', dest='list_browsers', action='store_true',
771
+ help='Prints out all detected browser that emrun is able to use with the --browser command and exits.')
772
+
773
+ parser.add_option('--browser', dest='browser', default='',
774
+ help='Specifies the browser executable to run the web page in.')
775
+
776
+ parser.add_option('--system_info', dest='system_info', action='store_true',
777
+ help='Prints information about the current system at startup.')
778
+
779
+ parser.add_option('--browser_info', dest='browser_info', action='store_true',
780
+ help='Prints information about the target browser to launch at startup.')
781
+
782
+ parser.add_option('--log_html', dest='log_html', action='store_true',
783
+ help='If set, information lines are printed out an HTML-friendly format.')
784
+
785
+ (options, args) = parser.parse_args(sys.argv)
786
+ emrun_options = options
787
+
788
+ if not options.browser:
789
+ if WINDOWS:
790
+ options.browser = 'start'
791
+ elif LINUX:
792
+ options.browser = which('xdg-open')
793
+ if not options.browser:
794
+ options.browser = 'firefox'
795
+ elif OSX:
796
+ options.browser = 'safari'
797
+
798
+ browsers = ['firefox', 'firefox_beta', 'firefox_aurora', 'firefox_nightly', 'chrome', 'chrome_canary', 'iexplore', 'safari', 'opera']
799
+ if options.list_browsers:
800
+ logi('emrun has automatically found the following browsers in the default install locations on the system:')
801
+ logi('')
802
+ for browser in browsers:
803
+ browser_exe = find_browser(browser)
804
+ if type(browser_exe) == list:
805
+ browser_exe = browser_exe[0]
806
+ if browser_exe:
807
+ logi(' - ' + browser + ': ' + browser_display_name(browser_exe) + ' ' + get_executable_version(browser_exe))
808
+ logi('')
809
+ logi('You can pass the --browser <id> option to launch with the given browser above.')
810
+ logi('Even if your browser was not detected, you can use --browser /path/to/browser/executable to launch with that browser.')
811
+ return
812
+
813
+ if len(args) < 2 and (options.system_info or options.browser_info):
814
+ options.no_server = options.no_browser = True # Don't run if only --system_info or --browser_info was passed.
815
+
816
+ if len(args) < 2 and not (options.no_server == True and options.no_browser == True):
817
+ logi('Usage: emrun filename.html')
818
+ return
819
+
820
+ file_to_serve = args[1] if len(args) > 1 else ''
821
+ cmdlineparams = args[2:] if len(args) > 2 else []
822
+
823
+ if options.serve_root:
824
+ serve_dir = os.path.abspath(options.serve_root)
825
+ else:
826
+ serve_dir = os.path.dirname(os.path.abspath(file_to_serve))
827
+ url = os.path.relpath(os.path.abspath(file_to_serve), serve_dir)
828
+ if len(cmdlineparams) > 0:
829
+ url += '?' + '&'.join(cmdlineparams)
830
+ url = 'http://localhost:'+str(options.port)+'/'+url
831
+
832
+ os.chdir(serve_dir)
833
+ logv('Web server root directory: ' + os.path.abspath('.'))
834
+
835
+ browser = find_browser(str(options.browser))
836
+ browser_exe = browser[0]
837
+ browser_args = []
838
+
839
+ if 'safari' in browser_exe.lower():
840
+ # Safari has a bug that a command line 'Safari http://page.com' does not launch that page,
841
+ # but instead launches 'file:///http://page.com'. To remedy this, must use the open -a command
842
+ # to run Safari, but unfortunately this will end up spawning Safari process detached from emrun.
843
+ if OSX:
844
+ browser = ['open', '-a', 'Safari'] + (browser[1:] if len(browser) > 1 else [])
845
+
846
+ processname_killed_atexit = 'Safari'
847
+ elif 'chrome' in browser_exe.lower():
848
+ processname_killed_atexit = 'chrome'
849
+ browser_args = ['--incognito', '--enable-nacl', '--enable-pnacl', '--disable-restore-session-state', '--enable-webgl', '--no-default-browser-check', '--no-first-run', '--allow-file-access-from-files']
850
+ # if options.no_server:
851
+ # browser_args += ['--disable-web-security']
852
+ elif 'firefox' in browser_exe.lower():
853
+ processname_killed_atexit = 'firefox'
854
+ elif 'iexplore' in browser_exe.lower():
855
+ processname_killed_atexit = 'iexplore'
856
+ browser_args = ['-private']
857
+ elif 'opera' in browser_exe.lower():
858
+ processname_killed_atexit = 'opera'
859
+
860
+ # In Windows cmdline, & character delimits multiple commmands, so must use ^ to escape them.
861
+ if browser_exe == 'cmd':
862
+ url = url.replace('&', '^&')
863
+ browser += browser_args + [url]
864
+
865
+ if options.kill_on_start:
866
+ kill_browser_process()
867
+
868
+ if options.system_info:
869
+ logi('Time of run: ' + time.strftime("%x %X"))
870
+ logi('Computer name: ' + socket.gethostname()) # http://stackoverflow.com/questions/799767/getting-name-of-windows-computer-running-python-script
871
+ logi('OS: ' + get_os_version() + ' with ' + str(get_system_memory()/1024/1024) + ' MB of System RAM')
872
+ logi('CPU: ' + get_cpu_infoline())
873
+ print_gpu_infolines()
874
+ if options.browser_info:
875
+ logi('Browser: ' + browser_display_name(browser[0]) + ' ' + get_executable_version(browser_exe))
876
+
877
+ # Suppress run warning if requested.
878
+ if options.no_emrun_detect:
879
+ emrun_not_enabled_nag_printed = True
880
+
881
+ global browser_stdout_handle, browser_stderr_handle
882
+ if options.log_stdout:
883
+ browser_stdout_handle = open(options.log_stdout, 'ab')
884
+ if options.log_stderr:
885
+ if options.log_stderr == options.log_stdout:
886
+ browser_stderr_handle = browser_stdout_handle
887
+ else:
888
+ browser_stderr_handle = open(options.log_stderr, 'ab')
889
+
890
+ if not options.no_browser:
891
+ logv("Executing %s" % ' '.join(browser))
892
+ if browser[0] == 'cmd':
893
+ serve_forever = True # Workaround an issue where passing 'cmd /C start' is not able to detect when the user closes the page.
894
+ browser_process = subprocess.Popen(browser)
895
+ if options.kill_on_exit:
896
+ atexit.register(kill_browser_process)
897
+
898
+ if not options.no_server:
899
+ logv('Starting web server in port ' + str(options.port))
900
+ httpd = HTTPWebServer(('', options.port), HTTPHandler)
901
+ try:
902
+ httpd.serve_forever()
903
+ except KeyboardInterrupt:
904
+ httpd.server_close()
905
+ httpd.server_close()
906
+
907
+ logv('Closed web server.')
908
+
909
+ if not options.no_browser:
910
+ if options.kill_on_exit:
911
+ kill_browser_process()
912
+ elif is_browser_process_alive():
913
+ logv('Not terminating browser process, pass --kill_exit to terminate the browser when it calls exit().')
914
+
915
+ return page_exit_code
916
+
917
+ if __name__ == '__main__':
918
+ sys.exit(main())