Merge pull request #12 from cordova-ubuntu/fix-debugging-handling

 Fix debugging handling 
diff --git a/CordovaUbuntu/CordovaViewInternal.qml b/CordovaUbuntu/CordovaViewInternal.qml
index 02dea8c..2f91f73 100644
--- a/CordovaUbuntu/CordovaViewInternal.qml
+++ b/CordovaUbuntu/CordovaViewInternal.qml
@@ -82,11 +82,27 @@
                 request.accept();
             }
 
+            onJavaScriptConsoleMessage: {
+                var msg = "[JS] (%1:%2) %3".arg(sourceId).arg(lineNumber).arg(message)
+                if (level === WebView.LogSeverityVerbose) {
+                    console.log(msg)
+                } else if (level === WebView.LogSeverityInfo) {
+                    console.info(msg)
+                } else if (level === WebView.LogSeverityWarning) {
+                    console.warn(msg)
+                } else if ((level === WebView.LogSeverityError) ||
+                           (level === WebView.LogSeverityErrorReport) ||
+                           (level === WebView.LogSeverityFatal)) {
+                    console.error(msg)
+                }
+            }
+
             context: WebContext {
                 id: webcontext
 
                 devtoolsEnabled: debuggingEnabled
-                devtoolsPort: debuggingEnabled ? 9222 : -1
+                devtoolsIp: debuggingDevtoolsIp
+                devtoolsPort: debuggingEnabled ? debuggingDevtoolsPort : -1
 
                 userScripts: [
                     UserScript {
@@ -113,8 +129,8 @@
                     msgId: "from-cordova"
                     contexts: [usContext]
                     callback: function(msg, frame) {
-                        CordovaWrapper.messageHandler(msg.args)
-                        console.log(JSON.stringify(msg.args))
+                        CordovaWrapper.messageHandler(msg.payload)
+                        console.log('Message payload', JSON.stringify(msg.payload))
                     }
                 }
             ]
diff --git a/bin/templates/project/cordova/lib/run.js b/bin/templates/project/cordova/lib/run.js
index 9f905d8..ba622a7 100644
--- a/bin/templates/project/cordova/lib/run.js
+++ b/bin/templates/project/cordova/lib/run.js
@@ -81,6 +81,27 @@
     });
 };
 
+function getDeviceInetAddress(target) {
+    function parseInetLines(lines) {
+        var ip = '';
+        for (var i = 0; i < lines.length; ++i) {
+            var match = /\s+inet\s+(\d+.\d+.\d+.\d+)?.*/.exec(lines[i])
+            if (match && match.length > 0 && match[1] != '127.0.0.1') {
+                ip = match[1];
+                break;
+            }
+        }
+        return ip
+    }
+    var lines = [];
+    if (target) {
+        lines = Devices.adbExec(target, 'shell ip -f inet addr').output.split('\n');
+    } else {
+        lines = Utils.execSync('ip -f inet addr').output.split('\n');
+    }
+    return parseInetLines(lines)
+}
+
 function runNative(rootDir, debug) {
     logger.info('Running Cordova');
     var ubuntuDir = path.join(rootDir, 'platforms', 'ubuntu');
@@ -91,7 +112,7 @@
     var cmd = './cordova-ubuntu www/';
     if (debug) {
         cmd = "DEBUG=1 " + cmd;
-        logger.warn('Debug enabled. Try pointing a Chrome/Chromium browser to http://127.0.0.1:9222');
+        logger.warn('Debug enabled. Devtools debug URL: http://' + getDeviceInetAddress(target) + ':9222');
     }
 
     logger.info('Launching the application.');
@@ -134,13 +155,13 @@
     Devices.adbExec(target, 'shell "cd /home/phablet/; pkcon install-local ' + names[0] + ' -p --allow-untrusted -y"', {silent: false});
 
     if (debug) {
-        logger.warn('Debug enabled. Try pointing a Chrome/Chromium browser to http://127.0.0.1:9222');
+        logger.warn('Debug enabled. Devtools debug URL: http://' + getDeviceInetAddress(target) + ':9222');
         Devices.adbExec(target, 'forward tcp:9222 tcp:9222');
     }
 
     logger.info('Launching the application on your device.');
 
-    return Devices.adbExecAsync(target, 'shell bash -c "ubuntu-app-launch  \\`ubuntu-app-triplet ' + appId + '\\`"').then(function () {
+    return Devices.adbExecAsync(target, 'shell "ubuntu-app-launch  \\`ubuntu-app-triplet ' + appId + '\\`"').then(function () {
         logger.rainbow('have fun!');
         Utils.popd();
     });
diff --git a/main.cpp b/main.cpp
index ffef445..4e676da 100644
--- a/main.cpp
+++ b/main.cpp
@@ -18,15 +18,18 @@
 #include <QtCore>
 #include <QApplication>
 #include <QtQuick>
+#include <QtNetwork/QNetworkInterface>
 
-static void customMessageOutput(
+const int kDebuggingDevtoolsDefaultPort = 9222;
+
+void customMessageOutput(
         QtMsgType type,
         const QMessageLogContext &,
         const QString &msg) {
 
     switch (type) {
     case QtDebugMsg:
-        if (qgetenv("DEBUG").size()) {
+        if (QString::fromUtf8(qgetenv("DEBUG")) == "1") {
             fprintf(stderr, "Debug: %s\n", msg.toStdString().c_str());
         }
         break;
@@ -39,9 +42,22 @@
     case QtFatalMsg:
         fprintf(stderr, "Fatal: %s\n", msg.toStdString().c_str());
         abort();
+        break;
     }
 }
 
+QString getDebuggingDevtoolsIp()
+{
+    QString host;
+    Q_FOREACH(QHostAddress address, QNetworkInterface::allAddresses()) {
+        if (!address.isLoopback() && (address.protocol() == QAbstractSocket::IPv4Protocol)) {
+            host = address.toString();
+            break;
+        }
+    }
+    return host;
+}
+
 int main(int argc, char *argv[]) {
     printf("\nApache Cordova native platform version %s is starting\n\n"
            , CORDOVA_UBUNTU_VERSION);
@@ -72,9 +88,32 @@
             (qEnvironmentVariableIsSet("DEBUG")
              && QString(qgetenv("DEBUG")) == "1");
 
+    // TODO revamp this for something cleaner, uniform
+    // and runtime bound
+#if !defined(NDEBUG)
+    debuggingEnabled = true;
+#endif
+
     view.rootContext()->setContextProperty(
                 "debuggingEnabled", debuggingEnabled);
 
+    QString debuggingDevtoolsIp;
+    int debuggingDevtoolsPort = -1;
+
+    if (debuggingEnabled) {
+      debuggingDevtoolsIp = getDebuggingDevtoolsIp();
+      debuggingDevtoolsPort = kDebuggingDevtoolsDefaultPort;
+
+      qDebug() << QString("Devtools URL: http://%1:%2")
+        .arg(debuggingDevtoolsIp)
+        .arg(debuggingDevtoolsPort);
+    }
+
+    view.rootContext()->setContextProperty(
+                "debuggingDevtoolsIp", debuggingDevtoolsIp);
+    view.rootContext()->setContextProperty(
+                "debuggingDevtoolsPort", debuggingDevtoolsPort);
+
     view.rootContext()->setContextProperty(
                 "www", wwwDir.absolutePath());