launcher/fx/src/main/java/org/apidesign/bck2brwsr/launcher/fximpl/WebDebug.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 11 Jun 2013 15:11:56 +0200
changeset 1173 aa82f9de8e33
parent 1169 c19ac78b940e
permissions -rw-r--r--
Pass in location of startpage file
     1 /**
     2  * Back 2 Browser Bytecode Translator
     3  * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
     4  *
     5  * This program is free software: you can redistribute it and/or modify
     6  * it under the terms of the GNU General Public License as published by
     7  * the Free Software Foundation, version 2 of the License.
     8  *
     9  * This program is distributed in the hope that it will be useful,
    10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12  * GNU General Public License for more details.
    13  *
    14  * You should have received a copy of the GNU General Public License
    15  * along with this program. Look for COPYING file in the top folder.
    16  * If not, see http://opensource.org/licenses/GPL-2.0.
    17  */
    18 package org.apidesign.bck2brwsr.launcher.fximpl;
    19 
    20 import com.sun.javafx.scene.web.Debugger;
    21 import java.io.File;
    22 import java.io.IOException;
    23 import java.io.InputStream;
    24 import java.io.InterruptedIOException;
    25 import java.io.OutputStream;
    26 import java.io.UnsupportedEncodingException;
    27 import java.lang.reflect.Method;
    28 import java.util.concurrent.ArrayBlockingQueue;
    29 import java.util.concurrent.Executors;
    30 import java.util.concurrent.TimeUnit;
    31 import java.util.concurrent.atomic.AtomicReference;
    32 import java.util.logging.Level;
    33 import java.util.logging.Logger;
    34 import javafx.application.Platform;
    35 import javafx.util.Callback;
    36 
    37 /** Simulates WebKit protocol over WebSockets.
    38  *
    39  * @author Jaroslav Tulach
    40  */
    41 abstract class WebDebug extends OutputStream 
    42 implements Callback<String, Void>, Runnable {
    43     private static final Logger LOG = Logger.getLogger(WebDebug.class.getName());
    44 
    45     private final Debugger debug;
    46     private final StringBuilder cmd = new StringBuilder();
    47     private final ToDbgInputStream toDbg;
    48     private final String ud;
    49     
    50     WebDebug(Debugger debug, String ud) throws Exception {
    51         this.debug = debug;
    52         this.ud = ud;
    53         toDbg = new ToDbgInputStream();
    54         debug.setEnabled(true);
    55         debug.setMessageCallback(this);
    56     }
    57     
    58     static WebDebug create(Debugger debug, String ud) throws Exception {
    59         WebDebug web = new WebDebug(debug, ud) {};
    60         
    61         Executors.newFixedThreadPool(1).execute(web);
    62         
    63         return web;
    64     }
    65 
    66     @Override
    67     public void run() {
    68         try {
    69             String p = System.getProperty("startpage.file");
    70             File f;
    71             if (p != null && (f = new File(p)).exists()) {
    72                 String[] args = {"--livehtml", f.getAbsolutePath()};
    73                 File dir = f.getParentFile();
    74                 cliHandler(args, toDbg, this, System.err, dir);
    75             }
    76         } catch (Exception ex) {
    77             LOG.log(Level.SEVERE, null, ex);
    78         }
    79     }
    80 
    81     @Override
    82     public void close() {
    83         try {
    84             toDbg.close();
    85         } catch (IOException ex) {
    86             LOG.log(Level.SEVERE, null, ex);
    87         }
    88     }
    89 
    90     @Override
    91     public Void call(String p) {
    92         assert p.indexOf('\n') == -1 : "No new line: " + p;
    93         LOG.log(Level.INFO, "toDbgr: {0}", p);
    94         toDbg.pushMsg(p);
    95         return null;
    96     }
    97 
    98     @Override
    99     public void write(int b) throws IOException {
   100         if (b == '\n') {
   101             final String msg = cmd.toString();
   102             Platform.runLater(new Runnable() {
   103                 @Override
   104                 public void run() {
   105                     LOG.log(Level.INFO, "toView: {0}", msg);
   106                     debug.sendMessage(msg);
   107                 }
   108             });
   109             cmd.setLength(0);
   110         } else {
   111             if (cmd.length() > 100000) {
   112                 LOG.log(Level.WARNING, "Too big:\n{0}", cmd);
   113             }
   114             cmd.append((char)b);
   115         }
   116     }   
   117 
   118     private void cliHandler(
   119         String[] args, InputStream is, OutputStream os, OutputStream err, File dir
   120     ) {
   121         try {
   122             Class<?> main = Class.forName("org.netbeans.MainImpl");
   123             Method m = main.getDeclaredMethod("execute", String[].class, InputStream.class, 
   124                 OutputStream.class, OutputStream.class, AtomicReference.class
   125             );
   126             m.setAccessible(true);
   127             System.setProperty("netbeans.user", ud);
   128             int ret = (Integer)m.invoke(null, args, is, os, err, null);
   129             LOG.log(Level.INFO, "Return value: {0}", ret);
   130         } catch (Exception ex) {
   131             LOG.log(Level.SEVERE, null, ex);
   132         } finally {
   133             LOG.info("Communication is over");
   134         }
   135         
   136     }
   137 
   138     private class ToDbgInputStream extends InputStream {
   139         private byte[] current;
   140         private int currentPos;
   141         private final ArrayBlockingQueue<byte[]> pending = new ArrayBlockingQueue<byte[]>(64);
   142 
   143         public ToDbgInputStream() {
   144         }
   145 
   146         @Override
   147         public int read() throws IOException {
   148             return read(null, 0, 1);
   149         }
   150         
   151         @Override
   152         public int read(byte[] arr, int offset, int len) throws IOException {
   153             if (current == null || current.length <= currentPos) {
   154                 for (;;) {
   155                     WebDebug.this.flush();
   156                     try {
   157                         current = pending.poll(5, TimeUnit.MILLISECONDS);
   158                         if (current == null) {
   159                             return 0;
   160                         }
   161                         break;
   162                     } catch (InterruptedException ex) {
   163                         throw (InterruptedIOException)new InterruptedIOException().initCause(ex);
   164                     }
   165                 }
   166                 LOG.info("Will return: " + new String(current));
   167                 currentPos = 0;
   168             }
   169             int cnt = 0;
   170             while (len-- > 0 && currentPos < current.length) {
   171                 final byte nextByte = current[currentPos++];
   172                 if (arr == null) {
   173                     return nextByte;
   174                 }
   175                 arr[offset + cnt++] = nextByte;
   176             }
   177             LOG.log(Level.INFO, "read returns: {0}", new String(arr, offset, cnt));
   178             return cnt;
   179         }
   180 
   181         private void pushMsg(String p) {
   182             try {
   183                 pending.offer((p + '\n').getBytes("UTF-8"));
   184             } catch (UnsupportedEncodingException ex) {
   185                 throw new IllegalStateException(ex);
   186             }
   187         }
   188     }
   189 }