[pypy-svn] r39822 - in pypy/dist/pypy/translator/js/examples: . console console/data console/test

fijal at codespeak.net fijal at codespeak.net
Sat Mar 3 17:13:46 CET 2007


Author: fijal
Date: Sat Mar  3 17:13:44 2007
New Revision: 39822

Modified:
   pypy/dist/pypy/translator/js/examples/console/client.py
   pypy/dist/pypy/translator/js/examples/console/console.py
   pypy/dist/pypy/translator/js/examples/console/data/console.html
   pypy/dist/pypy/translator/js/examples/console/session.py
   pypy/dist/pypy/translator/js/examples/console/test/test_console.py
   pypy/dist/pypy/translator/js/examples/over_client.py
   pypy/dist/pypy/translator/js/examples/overmind.py
Log:
Improve greatly a console example


Modified: pypy/dist/pypy/translator/js/examples/console/client.py
==============================================================================
--- pypy/dist/pypy/translator/js/examples/console/client.py	(original)
+++ pypy/dist/pypy/translator/js/examples/console/client.py	Sat Mar  3 17:13:44 2007
@@ -4,7 +4,8 @@
 from pypy.translator.js.examples.console.console import exported_methods
 
 class Glob(object):
-    pass
+    def __init__(self):
+        self.console_running = False
 
 glob = Glob()
 
@@ -18,12 +19,17 @@
         data_elem.removeChild(data_elem.childNodes[0])
     data_elem.appendChild(dom.document.createTextNode(data))
 
+def set_text(txt):
+    data_elem = dom.document.getElementById("data")
+    while data_elem.childNodes:
+        data_elem.removeChild(data_elem.childNodes[0])
+    data_elem.appendChild(dom.document.createTextNode(txt))    
+
 def refresh_console(msg):
     inp_elem = dom.document.getElementById("inp")
     #inp_elem.disabled = False
-    inp_elem.scrollIntoView()
-    log(msg[0])
     if msg[0] == "refresh":
+        inp_elem.scrollIntoView()
         data = msg[1]
         log(data)
         exported_methods.refresh_empty(glob.sess_id, refresh_console)
@@ -52,10 +58,30 @@
         #else:
         exported_methods.refresh(glob.sess_id, cmd + "\n", refresh_console)
 
-def console_onload():
-    #createLoggingPane(True)
+def nothing(msg):
+    pass
+
+def cleanup_console():
+    inp_elem = dom.document.getElementById("inp")
+    inp_elem.disabled = True
+    set_text("")
+    exported_methods.kill_console(glob.sess_id, nothing)
+
+def load_console(python="python"):
+    if glob.console_running:
+        cleanup_console()
     inp_elem = dom.document.getElementById("inp")
+    main = dom.document.getElementById("main")
+    main.style.visibility = "visible"
+    inp_elem.disabled = False
     inp_elem.focus()
+    glob.console_running = True
+    exported_methods.get_console(python, set_sessid)
+
+def console_onload():
+    #createLoggingPane(True)
+    #inp_elem = dom.document.getElementById("inp")
+    #inp_elem.focus()
     dom.document.onkeypress = keypressed
-    exported_methods.get_console(set_sessid)
+    #exported_methods.get_console("python", set_sessid)
 

Modified: pypy/dist/pypy/translator/js/examples/console/console.py
==============================================================================
--- pypy/dist/pypy/translator/js/examples/console/console.py	(original)
+++ pypy/dist/pypy/translator/js/examples/console/console.py	Sat Mar  3 17:13:44 2007
@@ -14,7 +14,7 @@
 
 commproxy.USE_MOCHIKIT = True
 
-FUNCTION_LIST = ["console_onload"]
+FUNCTION_LIST = ["load_console", "console_onload"]
 
 class Ignore(Exception):
     pass
@@ -23,13 +23,26 @@
     import client
     return rpython2javascript(client, FUNCTION_LIST)
 
+def line_split(ret, max_len):
+    to_ret = []
+    for line in ret.split("\n"):
+        if len(line) > max_len:
+            to_ret += [line[i*max_len:(i+1)*max_len] for i in
+                       range(len(line)/max_len - 1)]
+            i += 1
+        else:
+            i = 0
+        to_ret.append(line[i*max_len:])
+    return "\n".join(to_ret)
+
+
 class Sessions(object):
     def __init__(self):
         self.sessions = {}
         self.updating = {}
 
-    def new_session(self):
-        ip = Interpreter("python")
+    def new_session(self, python="python"):
+        ip = Interpreter(python)
         self.sessions[ip.pid] = ip
         self.updating[ip.pid] = False
         return ip.pid
@@ -44,16 +57,23 @@
         self.updating[pid] = False
         if not ret:
             return ""
-        return ret
+        MAX_LEN = 80
+        return line_split(ret, MAX_LEN)
+
+    def kill_session(self, pid):
+        ip = self.sessions[pid]
+        ip.pipe.stdin.close()
+        del self.sessions[pid]
+        del self.updating[pid]
 
 # We hack here, cause in exposed methods we don't have global 'server'
 # state
 sessions = Sessions()
 
 class ExportedMethods(server.ExportedMethods):
-    @callback(retval=int)
-    def get_console(self):
-        retval = sessions.new_session()
+    @callback(args=[str], retval=int)
+    def get_console(self, python="python"):
+        retval = sessions.new_session(python)
         return retval
 
     @callback(retval=[str])
@@ -76,23 +96,34 @@
         except Ignore:
             return ["ignore"]
 
+    @callback()
+    def kill_console(self, pid=0):
+        sessions.kill_session(int(pid))
+
 exported_methods = ExportedMethods()
 
-class Handler(server.Handler):
+static_dir = py.path.local(__file__).dirpath().join("data")
+
+class Root(server.Collection):
     exported_methods = exported_methods
-    static_dir = py.path.local(__file__).dirpath().join("data")
-    index = server.Static(static_dir.join("console.html"))
+    #index = server.Static(static_dir.join("console.html"))
+    index = server.FsFile(static_dir.join("console.html"))
     MochiKit = server.StaticDir('MochiKit')
 
     def source_js(self):
-        if hasattr(self.server, 'source'):
-            source = self.server.source
+        if hasattr(self.server, 'source_console'):
+            source = self.server.source_console
         else:
             source = js_source()
-            self.server.source = source
+            self.server.source_console = source
         return "text/javascript", source
     source_js.exposed = True
 
+class Handler(server.NewHandler):
+    application = Root()
+    application.some = Root()
+    application.other = Root()
+
 if __name__ == '__main__':
     addr = ('', 8007)
     httpd = server.create_server(server_address=addr, handler=Handler,

Modified: pypy/dist/pypy/translator/js/examples/console/data/console.html
==============================================================================
--- pypy/dist/pypy/translator/js/examples/console/data/console.html	(original)
+++ pypy/dist/pypy/translator/js/examples/console/data/console.html	Sat Mar  3 17:13:44 2007
@@ -7,9 +7,18 @@
    </style>
 </head>
 <body onload="console_onload()">
-   <h3>Python console</h3>
-   <pre id="data"></pre>
-   &gt;&gt;&gt; <input id="inp" size="80" type="text" autocomplete="off"/>
-   <p id="error"></p>
+   <div style="visibility:visible" id="navbar">
+     <ul>
+       <li><a href="javascript:load_console('python')">Plain CPython console</a></li>
+       <li><a href="javascript:load_console('pypy-c')">pypy-c</a></li>
+       <li><a href="javascript:cleanup_console()">kill console</a></li>
+     </ul>
+   </div>
+   <div style="visibility:hidden" id="main">
+     <h3>Python console</h3>
+     <pre id="data"></pre>
+     &gt;&gt;&gt; <input id="inp" size="80" type="text" autocomplete="off"/>
+     <p id="error"></p>
+   </div>
 </body>
 </html>
\ No newline at end of file

Modified: pypy/dist/pypy/translator/js/examples/console/session.py
==============================================================================
--- pypy/dist/pypy/translator/js/examples/console/session.py	(original)
+++ pypy/dist/pypy/translator/js/examples/console/session.py	Sat Mar  3 17:13:44 2007
@@ -30,7 +30,7 @@
     def timeout_read(self, fd, timeout):
         timer = Timer(timeout)
         try:
-            data = fd.recv(1024)
+            data = fd.recv(10024)
         except Interrupted:
             data = None
         else:

Modified: pypy/dist/pypy/translator/js/examples/console/test/test_console.py
==============================================================================
--- pypy/dist/pypy/translator/js/examples/console/test/test_console.py	(original)
+++ pypy/dist/pypy/translator/js/examples/console/test/test_console.py	Sat Mar  3 17:13:44 2007
@@ -1,12 +1,18 @@
 
-import py
-py.test.skip("XXX")
+def test_line_skip():
+    from pypy.translator.js.examples.console.console import line_split
 
-from pypy.translator.js.examples.console import console
+    assert line_split("asdf", 80) == "asdf"
+    assert line_split("a b c d", 3) == "a b\n c d"
+    assert line_split("a b c d e f g h i j", 3) == "a b\n c \nd e\n f \ng h\n i j"
 
 def test_run_console():
     """ Check if we can read anything
     """
+    import py
+    py.test.skip("XXX")
+
+    from pypy.translator.js.examples.console import console
     pipe = console.run_console("python")
     pipe.stdin.close()
     t = False

Modified: pypy/dist/pypy/translator/js/examples/over_client.py
==============================================================================
--- pypy/dist/pypy/translator/js/examples/over_client.py	(original)
+++ pypy/dist/pypy/translator/js/examples/over_client.py	Sat Mar  3 17:13:44 2007
@@ -2,16 +2,12 @@
 """ Client side of overmind.py
 """
 
-from pypy.translator.js.examples.overmind import exported_methods
 from pypy.translator.js.modules import dom
 
 def callback(port):
     hname = dom.window.location.hostname
     dom.window.location.assign("http://%s:%d" % (hname, port))
 
-def launch_console():
-    exported_methods.launch_console(callback)
-
 def bnb_redirect():
     loc = dom.window.location
     new_loc = loc.protocol + "//" + loc.hostname + ":7070"

Modified: pypy/dist/pypy/translator/js/examples/overmind.py
==============================================================================
--- pypy/dist/pypy/translator/js/examples/overmind.py	(original)
+++ pypy/dist/pypy/translator/js/examples/overmind.py	Sat Mar  3 17:13:44 2007
@@ -10,47 +10,36 @@
 from pypy.rpython.extfunc import _callable
 from pypy.rpython.ootypesystem.bltregistry import described
 from pypy.translator.js.main import rpython2javascript
+from pypy.translator.js.examples.console import console
 
 import os
 import py
 
-FUNCTION_LIST = ['launch_console', 'bnb_redirect']
+FUNCTION_LIST = ['bnb_redirect']
 TIMEOUT = 300
 pids = []
 
-def launch_console_in_new_prcess():
-    from pypy.translator.js.examples import pythonconsole
-    httpd = server.create_server(server_address=('', 0),
-                        handler=pythonconsole.RequestHandler,
-                        server=pythonconsole.Server)
-    port = httpd.server_port
-    pythonconsole.httpd = httpd
-    pid = server.start_server_in_new_process(httpd, timeout=TIMEOUT)
-    del httpd
-    pids.append(pid)
-    return port
-
-class ExportedMethods(server.ExportedMethods):
-    @callback(retval=int)
-    def launch_console(self):
-        """ Note that we rely here on threads not being invoked,
-        if we want to make this multiplayer, we need additional locking
-        XXX
-        """
-        return launch_console_in_new_prcess()
-
-exported_methods = ExportedMethods()
+#def launch_console_in_new_prcess():
+#    from pypy.translator.js.examples import pythonconsole
+#    httpd = server.create_server(server_address=('', 0),
+#                        handler=pythonconsole.RequestHandler,
+#                        server=pythonconsole.Server)
+#    port = httpd.server_port
+#    pythonconsole.httpd = httpd
+#    pid = server.start_server_in_new_process(httpd, timeout=TIMEOUT)
+#    del httpd
+#    pids.append(pid)
+#    return port
 
 def js_source(function_list):
     import over_client
     return rpython2javascript(over_client, FUNCTION_LIST)
 
-class Handler(server.Handler):
-    static_dir = str(py.path.local(__file__).dirpath().join("data"))
-    index = server.Static()
-    console = server.Static(os.path.join(static_dir, "launcher.html"))
-    terminal = server.Static(os.path.join(static_dir, "terminal.html"))
-    exported_methods = exported_methods
+class Root(server.Collection):
+    static_dir = py.path.local(__file__).dirpath().join("data")
+    index = server.FsFile(static_dir.join("index.html"))
+    terminal = server.Static(static_dir.join("terminal.html"))
+    console = console.Root()
 
     def source_js(self):
         if hasattr(self.server, 'source'):
@@ -70,12 +59,18 @@
            <body onload="bnb_redirect()">
            </body>
         </html>'''
-    bnb.exposed = True
+    bnb.exposed = True    
+
+class Handler(server.NewHandler):
+    application = Root()
+    #console = server.Static(os.path.join(static_dir, "launcher.html"))
 
 if __name__ == '__main__':
     try:
         addr = ('', 8008)
-        httpd = server.create_server(server_address=addr, handler=Handler)
+        from pypeers.httpserver import GreenHTTPServer
+        httpd = server.create_server(server_address=addr, handler=Handler,
+                                     server=GreenHTTPServer)
         httpd.serve_forever()
     except KeyboardInterrupt:
         for pid in pids:



More information about the Pypy-commit mailing list