Commits

Ruslan Osmanov committed 438498a

Dev

Comments (0)

Files changed (9)

-if (document.activeElement.tagName == 'TEXTAREA') {
-
+var ae = document.activeElement;
+if (ae.tagName == 'TEXTAREA') {
+	console.log("content.js ae", ae);
+	chrome.runtime.sendMessage({
+		bee_msg: 'input',
+		bee_input: ae.innerHTML
+	},
+	function (response) {
+		console.log("content.js received", response);
+		ae.innerHTML = response;
+	});
 }
 		chrome.tabs.executeScript(null, {file: "content.js"});
 	}
 });
+
+chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
+	console.log("onMessage, request", request);
+	if (request.bee_msg == 'input') {
+		chrome.runtime.sendNativeMessage(
+			'com.ruslan_osmanov.bee',
+			{text: request.bee_input},
+			function (response) {
+				console.log("eventPage.js received", response);
+				sendResponse(response);
+			}
+		);
+	}
+});
 		"activeTab",
 		"tabs",
 		"storage",
+		"nativeMessaging",
 		"http://*/*",
 		"https://*/*"
 	],
-#!/bin/bash -
-# vim: noet ts=4 sts=4 sw=4
-#
-# Native messaging host for the Bee Google Chrome extension
-#
-# Copyright © 2014 Ruslan Osmanov <rrosmanov@gmail.com>
-
-# Parse user configuration
-conf="$HOME/.config/beectl.conf"
-if [ -f "$conf" ]
-then
-	OLDIFS="$IFS"
-	IFS="="
-	while read -r k v
-	do
-		case "$k" in
-			bee_editor*)
-				bee_editor="${v//\"/}";;
-		esac
-	done < "$conf"
-	IFS=$OLDIFS
-fi
-
-# Guess editor
-if [ -z "$bee_editor" ]
-then
-	#popular_editors=("${bee_editor}" 'gedit' 'kate' 'sublime' 'gvim' 'qvim' 'emacs' 'leafpad')
-	for e in ${popular_editors[@]}
-	do
-		path=$(command -v "$e")
-		if [ $path ]; then
-			echo "bee_editor assigned to $path"
-			bee_editor="$path"
-			break
-		fi
-	done
-fi
-
-# Fallback
-: ${bee_editor:=$VISUAL}
-
-if [ -z "${bee_editor}" ]
-then
-	echo >&2 "No editor found"
-	exit 1
-elif [ `expr match "$bee_editor" '\(.*vim\)'` ]
-then
-	# No-fork option for vim family
-	bee_editor="$bee_editor -f"
-fi
-
-# Open temporary file with editor (assuming we run it in foreground)
-tmpfile=$(mktemp -t "${0##*/}.XXXXXXXXXX")
-cat /dev/stdin > "$tmpfile"
-$bee_editor "$tmpfile"
-
-cat "$tmpfile"
-rm "$tmpfile"
+#!/usr/bin/env python3
+
+import json
+import struct
+import re
+#import io
+import os.path
+import sys
+import tempfile
+
+
+def which(exe):
+    for dir in os.environ['PATH'].split(':'):
+        path = os.path.join(dir, exe)
+        if os.path.exists(path):
+            return path
+    return False
+
+
+def parse_user_config():
+    filename = os.path.expanduser("~/.config/beectl.conf")
+    if (not os.path.exists(filename)):
+        return None
+
+    conf = {}
+    with open(filename) as fp:
+        for line in iter(fp.readline, ''):
+            c = re.split('[\s\=]+', line, 1)
+            conf[c[0]] = c[1]
+
+    return conf
+
+
+def get_editor(conf):
+    if 'bee_editor' in conf:
+        return ['bee_editor']
+
+    for e in ['gedit', 'kate', 'sublime', 'gvim',
+              'qvim', 'macvim', 'emacs', 'leafpad']:
+        path = which(e)
+        if which(e):
+            return path
+
+    return os.getenv('EDITOR')
+
+
+def main():
+    fp_log = open('/tmp/beectl.py.log', "a")
+
+    conf = parse_user_config()
+    bee_editor = get_editor(conf)
+    fp_log.write("Conf parsed, bee_editor: " + bee_editor + "\n")
+    args = []
+
+    if not bee_editor:
+        sys.exit("No editor found")
+
+    # no-fork option for vim family
+    if re.match('.*vim', bee_editor):
+        args.append('-f')
+
+    fp_log.write("bee_editor after vim check: " + bee_editor + "\n")
+
+    # 1st 4 bytes is the message type
+    text_len_bytes = sys.stdin.buffer.read(4)
+    fp_log.write("text_len_bytes: %s\n" % text_len_bytes.decode('UTF-8'))
+
+    if len(text_len_bytes) == 0:
+        fp_log.write("len(text_len_bytes) == 0. Exit.\n")
+        fp_log.close()
+        sys.exit(0)
+
+    fp_log.write("unpacking text_len_bytes\n")
+    text_len = struct.unpack('I', text_len_bytes)[0]
+    fp_log.write("text_len: %i\n" % text_len)
+
+    json_text = sys.stdin.buffer.read(text_len)
+    fp_log.write("read text: %s\n" % json_text)
+    text = json.loads(json_text.decode('UTF-8'))
+    fp_log.write("text: %s\n" % text['text'])
+
+    f = tempfile.mkstemp('', 'chrome_bee_')
+    os.write(f[0], bytes(text['text'], 'UTF-8'))
+    fp_log.write("written text to tmp file %s\n" % f[1])
+    args.append(f[1])
+
+    os.execvp(bee_editor, args)
+    response = os.read(f[0])
+    #fp_log.write("response from editor: " + response + "\n")
+    os.close(f[0])
+    sys.unlink(f[1])
+
+    # Write message size
+    sys.stdout.buffer.write(json.dumps(struct.pack('I', len(response))))
+    # Write message itself
+    sys.stdout.buffer.write(response)
+    sys.stdout.flush()
+    fp_log.write("written response to stdout\n=============\n\n\n")
+    fp_log.close()
+
+    sys.exit(0)
+
+
+def my_excepthook(type, value, tb):
+    fp_log = open('/tmp/beectl.py.log', "a")
+    fp_log.write("my exception hook: type: %s value: %s", {0: type, 1: value})
+    fp_log.close()
+
+    # the following line does the default (prints it to err)
+    sys.__excepthook__(type, value, tb)
+
+
+if __name__ == '__main__':
+    #sys.excepthook = my_excepthook
+    main()
+#!/bin/bash -
+# vim: noet ts=4 sts=4 sw=4
+#
+# Native messaging host for the Bee Google Chrome extension
+#
+# Copyright © 2014 Ruslan Osmanov <rrosmanov@gmail.com>
+
+# Parse user configuration
+conf="$HOME/.config/beectl.conf"
+if [ -f "$conf" ]
+then
+	OLDIFS="$IFS"
+	IFS="="
+	while read -r k v
+	do
+		case "$k" in
+			bee_editor*)
+				bee_editor="${v//\"/}";;
+		esac
+	done < "$conf"
+	IFS=$OLDIFS
+fi
+
+# Guess editor
+if [ -z "$bee_editor" ]
+then
+	popular_editors=('gedit' 'kate' 'sublime' 'gvim' 'qvim' 'emacs' 'leafpad')
+	for e in ${popular_editors[@]}
+	do
+		path=$(command -v "$e")
+		if [ $path ]; then
+			echo "bee_editor assigned to $path"
+			bee_editor="$path"
+			break
+		fi
+	done
+fi
+
+# Fallback
+: ${bee_editor:=$VISUAL}
+
+log=/home/ruslan/projects/chrome/bee/log
+
+if [ -z "${bee_editor}" ]
+then
+	echo >&2 "No editor found"
+	exit 1
+elif [ `expr match "$bee_editor" '\(.*vim\)'` ]
+then
+	# No-fork option for vim family
+	bee_editor="$bee_editor -f"
+fi
+
+# Open temporary file with editor (assuming we run it in foreground)
+tmpfile=$(mktemp -t "${0##*/}.XXXXXXXXXX")
+# Skip 1st 4 bytes
+read -N4 -u0 $len
+echo "len = $len" >> $log
+cat /dev/stdin > $tmpfile
+
+echo $bee_editor $tmpfile >> $log
+$bee_editor "$tmpfile" >/dev/null 2>&1
+echo "bee editor closed sending response" >> $log
+
+cat "$tmpfile" | tee $log 
+echo "removing file $tmpfile" >> $log
+rm "$tmpfile"

server/com.ruslan_osmanov.bee.json

 {
 	"name": "com.ruslan_osmanov.bee",
 	"description": "Bee - Browser's external editor",
-	"path": "/opt/bin/beectl",
+	"path": "/opt/osmanov/chrome/beectl",
 	"type": "stdio",
 	"allowed_origins": [
-		"chrome-extension://dbaifkpgelpeecacambibmaochndgooj"
-		]
+		"chrome-extension://dbaifkpgelpeecacambibmaochndgooj/"
+	]
 }
+#!/bin/bash -
+# vim: noet ts=4 sts=4 sw=4
+#
+# Native messaging host setup.
+# Requires root privileges
+#
+# Copyright © 2014 Ruslan Osmanov <rrosmanov@gmail.com>
+
+if [ $(uname -s) == 'Darwin' ]
+then
+	manifest_dir='/Library/Google/Chrome/NativeMessagingHosts'
+else
+	manifest_dir='/etc/opt/chrome/native-messaging-hosts'
+fi
+host_dir='/opt/osmanov/chrome/'
+host_name=com.ruslan_osmanov.bee
+host_file=beectl
+
+install -D -m 0644 "${PWD}/server/${host_name}.json" "${manifest_dir}/${host_name}.json"
+install -D -m 0755 "${PWD}/server/${host_file}" "${host_dir}/${host_file}"
+
+echo "Native messaging host ${host_name} has been installed into $host_dir."
+<html>
+<head>
+	<meta http-equiv="content-type" content="text/html; charset=utf-8" />
+
+	<title>testing bee</title>
+</head>
+<body>
+	<textarea name="t" id=t rows="8" cols="40">default text</textarea>
+</body>
+</html>