• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1var tcpUI = tcpUI || {};
2var tcpServer;
3var commandWindow;
4
5tcpUI.create = function() {
6  if (commandWindow && !commandWindow.contentWindow.closed) {
7    commandWindow.focus();
8  } else {
9    chrome.app.window.create('index.html',
10        {id: "mainwin", innerBounds: {width: 500, height: 309, left: 0}},
11	    function(w) { commandWindow = w; });
12  }
13}
14
15/**
16 * Listens for the app launching then creates the window
17 *
18 * @see https://developer.chrome.com/apps/app_runtime
19 * @see https://developer.chrome.com/apps/app_window
20 */
21chrome.app.runtime.onLaunched.addListener(tcpUI.create);
22
23// event logger
24var log = (function(){
25  var logLines = [];
26  var logListener = null;
27
28  var output=function(str) {
29    if (str.length>0 && str.charAt(str.length-1)!='\n') {
30      str+='\n'
31    }
32    logLines.push(str);
33    if (logListener) {
34      logListener(str);
35    }
36  };
37
38  var addListener=function(listener) {
39    logListener=listener;
40    // let's call the new listener with all the old log lines
41    for (var i=0; i<logLines.length; i++) {
42      logListener(logLines[i]);
43    }
44  };
45
46  return {output: output, addListener: addListener};
47})();
48
49function onAcceptCallback(tcpConnection, socketInfo) {
50  var info="["+socketInfo.peerAddress+":"+socketInfo.peerPort+"] Connection accepted!";
51  log.output(info);
52  console.log(socketInfo);
53  tcpConnection.addDataReceivedListener(function(data) {
54    var lines = data.split(/[\n\r]+/);
55    for (var i=0; i<lines.length; i++) {
56      var line=lines[i];
57      if (line.length>0) {
58        var info="["+socketInfo.peerAddress+":"+socketInfo.peerPort+"] "+line;
59        log.output(info);
60
61        var cmd=line.split(/\s+/);
62        try {
63          tcpConnection.sendMessage(Commands.run(cmd[0], cmd.slice(1)));
64        } catch (ex) {
65          tcpConnection.sendMessage(ex);
66        }
67      }
68    }
69  });
70};
71
72function startServer(addr, port) {
73  if (tcpServer) {
74    tcpServer.disconnect();
75  }
76  tcpServer = new TcpServer(addr, port);
77  tcpServer.listen(onAcceptCallback);
78}
79
80
81function stopServer() {
82  if (tcpServer) {
83    tcpServer.disconnect();
84    tcpServer=null;
85  }
86}
87
88function getServerState() {
89  if (tcpServer) {
90    return {isConnected: tcpServer.isConnected(),
91      addr: tcpServer.addr,
92      port: tcpServer.port};
93  } else {
94    return {isConnected: false};
95  }
96}
97
98tcpUI.startServer = function(addr, port) {
99  startServer(addr, port);
100}
101
102tcpUI.stopServer = function() {
103  stopServer();
104}
105