[Sciviews-commits] r352 - in komodo/SciViews-K: components content/js
noreply at r-forge.r-project.org
noreply at r-forge.r-project.org
Mon Feb 14 22:53:06 CET 2011
Author: prezez
Date: 2011-02-14 22:53:06 +0100 (Mon, 14 Feb 2011)
New Revision: 352
Added:
komodo/SciViews-K/components/svIUtils.idl
komodo/SciViews-K/components/svUtils.py
komodo/SciViews-K/content/js/r_new.js
Modified:
komodo/SciViews-K/components/Conscript
Log:
Alternative interface to R implemented as XPCOM object in python (svUtils, with javascript wrapper: sv.rnew)
Modified: komodo/SciViews-K/components/Conscript
===================================================================
--- komodo/SciViews-K/components/Conscript 2011-01-31 10:50:49 UTC (rev 351)
+++ komodo/SciViews-K/components/Conscript 2011-02-14 21:53:06 UTC (rev 352)
@@ -1,27 +1,27 @@
#!/usr/local/bin/perl
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
-#
+#
# The contents of this file are subject to the Mozilla Public License
# Version 1.1 (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
-#
+#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
# License for the specific language governing rights and limitations
# under the License.
-#
+#
# The Original Code is SciViews code.
-#
+#
# The Initial Developer of the Original Code is ActiveState Software Inc.
# Portions created by ActiveState Software Inc are Copyright (C) 2000-2007
# ActiveState Software Inc. All Rights Reserved.
-#
+#
# Contributor(s):
# Ph. Grosjean <phgrosjean at sciviews.org>
# ActiveState Software Inc
-#
+#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
@@ -33,7 +33,7 @@
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
-#
+#
# ***** END LICENSE BLOCK *****
Import(
@@ -51,3 +51,4 @@
'havePy2to3',
);
$cons->InstallXpcomComponent('koRLinter.py');
+$cons->InstallXpcomComponent('svUtils.py');
Added: komodo/SciViews-K/components/svIUtils.idl
===================================================================
--- komodo/SciViews-K/components/svIUtils.idl (rev 0)
+++ komodo/SciViews-K/components/svIUtils.idl 2011-02-14 21:53:06 UTC (rev 352)
@@ -0,0 +1,44 @@
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License
+ * Version 1.1 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+ * License for the specific language governing rights and limitations
+ * under the License.
+ *
+ * The Original Code is SciViews-K by Philippe Grosjean et al.
+ *
+ * Contributor(s):
+ * Philippe Grosjean
+ * ActiveState Software Inc (code inspired from)
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#include "nsISupports.idl"
+#include "nsISimpleEnumerator.idl"
+
+[scriptable, uuid(5f82d460-37b6-11e0-b897-0002a5d5c51b)]
+interface svIUtils : nsISupports {
+ nsISimpleEnumerator getproc(in string propertyName);
+ string execInR(in wstring command, in string host, in long port);
+ void execInRBgr(in wstring command, in string host, in long port);
+ attribute wstring lastCommand;
+ attribute wstring lastResult;
+};
Added: komodo/SciViews-K/components/svUtils.py
===================================================================
--- komodo/SciViews-K/components/svUtils.py (rev 0)
+++ komodo/SciViews-K/components/svUtils.py 2011-02-14 21:53:06 UTC (rev 352)
@@ -0,0 +1,151 @@
+#!python
+# ***** BEGIN LICENSE BLOCK *****
+# Version: MPL 1.1/GPL 2.0/LGPL 2.1
+#
+# The contents of this file are subject to the Mozilla Public License
+# Version 1.1 (the "License"); you may not use this file except in
+# compliance with the License. You may obtain a copy of the License at
+# http://www.mozilla.org/MPL/
+#
+# Software distributed under the License is distributed on an "AS IS"
+# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+# License for the specific language governing rights and limitations
+# under the License.
+#
+# Author:
+# Kamil Barton <kamil.barton at go2.pl>
+
+# Alternatively, the contents of this file may be used under the terms of
+# either the GNU General Public License Version 2 or later (the "GPL"), or
+# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+# in which case the provisions of the GPL or the LGPL are applicable instead
+# of those above. If you wish to allow use of your version of this file only
+# under the terms of either the GPL or the LGPL, and not to allow others to
+# use your version of this file under the terms of the MPL, indicate your
+# decision by deleting the provisions above and replace them with the notice
+# and other provisions required by the GPL or the LGPL. If you do not delete
+# the provisions above, a recipient may use your version of this file under
+# the terms of any one of the MPL, the GPL or the LGPL.
+#
+# ***** END LICENSE BLOCK *****
+
+
+## This is interface for communication with R through socket connection
+
+from xpcom import components, nsError, COMException
+from xpcom._xpcom import getProxyForObject, PROXY_SYNC, PROXY_ALWAYS, PROXY_ASYNC
+import os, sys, re
+#import tempfile
+import string
+#import process
+#import koprocessutils
+from xpcom.server.enumerator import SimpleEnumerator
+import socket
+#from threading import Thread
+import threading
+
+
+import logging
+log = logging.getLogger('svUtils')
+
+class svUtils:
+ _com_interfaces_ = [components.interfaces.svIUtils]
+ _reg_desc_ = "SciViews-K utilities"
+ _reg_clsid_ = "{5f82d460-37b6-11e0-b897-0002a5d5c51b}"
+ _reg_contractid_ = "@sciviews.org/svUtils;1"
+
+ def __init__(self):
+ observerSvc = components.classes["@mozilla.org/observer-service;1"].\
+ getService(components.interfaces.nsIObserverService)
+
+ self._proxiedObsSvc = getProxyForObject(1, \
+ components.interfaces.nsIObserverService, \
+ observerSvc, PROXY_ALWAYS | PROXY_SYNC)
+
+ self.lastCommand = u''
+ self.lastResult = u''
+ pass
+
+ def _asSString(self, s):
+ ret = components.classes["@mozilla.org/supports-string;1"] \
+ .createInstance(components.interfaces.nsISupportsString)
+ ret.data = str(s)
+ return(ret)
+
+ def getproc(self, propertyName):
+# TODO: error handling here
+# TODO: checking for correct propertyName
+ ret = []
+ if sys.platform.startswith('win'):
+ from win32com.client import GetObject
+ WMI = GetObject('winmgmts:')
+ processes = WMI.ExecQuery('select ' + propertyName + \
+ ' from Win32_Process where Name="Rgui.exe" or Name="R.exe" or Name="Rterm.exe"')
+ if len(processes) > 0 :
+ for p in processes:
+ #ret.append([p.Properties_('Name').Value, p.Properties_('ProcessId').Value])
+ ##ret.append(p.Properties_('ExecutablePath').Value) 'CommandLine'
+ elem = components.classes["@mozilla.org/supports-string;1"] \
+ .createInstance(components.interfaces.nsISupportsString)
+ ret.append(p.Properties_(propertyName).Value)
+ else:
+ propertyName = {
+ 'Handle': 'pid',
+ 'ProcessId': 'pid',
+ 'CommandLine': 'cmd'
+ }[propertyName]
+
+ import subprocess
+ ret = subprocess.Popen(['ps', '--no-header', '-o', propertyName, '-C', 'R'],
+ stdout=subprocess.PIPE).communicate()[0].split("\n")
+ ret = [el for el in ret if el != '']
+
+ ret = map(self._asSString, ret);
+ return SimpleEnumerator(ret)
+
+
+ def execInR(self, command, host, port):
+ """
+ This should send command to R through a socket connection and return the
+ output
+ """
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ s.connect((host, port))
+ s.settimeout(5)
+ # TODO: allow for <<<h>>>
+ s.send('<<<id=SciViewsK>>><<<e>>>' + command)
+ s.shutdown(socket.SHUT_WR) # does not work without shutdown, why?
+ result = ''
+ while 1:
+ data = s.recv(1024)
+ if not data: break
+ result += data
+ s.close()
+ return unicode(result)
+
+ def execInRBgr(self, command, host='localhost', port=8888):
+ t = threading.Thread(target=self.rconnect, args=(command, host, port))
+ #t.setDaemon(True)
+ t.start()
+
+ def rconnect(self, command, host, port):
+ self.lastCommand = unicode(command)
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ s.connect((host, port))
+ s.settimeout(None)
+ s.send('<<<id=SciViewsK>>><<<e>>>' + command)
+ s.shutdown(socket.SHUT_WR) # does not work without shutdown, why?
+ result = ''
+ # notify after each chunk, and at the end
+ while 1:
+ data = s.recv(1024)
+ if not data: break
+ self._proxiedObsSvc.notifyObservers(None, 'r-command-chunk', data)
+ result += data
+ self._proxiedObsSvc.notifyObservers(None, 'r-command-finished', result)
+ s.close()
+ self.lastResult = unicode(result)
+ #try:
+ self._proxiedObsSvc.notifyObservers(None, 'r-command-executed', result)
+ #except Exception:
+ #log.exception("r-command-executed notification failed")
Added: komodo/SciViews-K/content/js/r_new.js
===================================================================
--- komodo/SciViews-K/content/js/r_new.js (rev 0)
+++ komodo/SciViews-K/content/js/r_new.js 2011-02-14 21:53:06 UTC (rev 352)
@@ -0,0 +1,112 @@
+//{ }
+
+// 's.rnew' object is an interface to R implemented mostly in python
+// The workhorse is 'svUtils' XPCOM interface
+//.command (Read only) last command evaluated
+//.result (Read only) last result returned
+//.getRProc(property) get information on currently running R processes
+// (property is one of 'Handle','ProcessId' or 'CommandLine'
+//.setObserver(callback) set callback function for R command
+//.removeObserver
+//.rEval(command, callback) evaluate in R, optional callback (if not provided,
+// the most recent one is used)
+//.rEvalQuick(command) - do 'quick' evaluation in R, and
+//return the result
+
+
+
+sv.rnew = {};
+
+(function() {
+ var _this = this;
+
+// get string from nsISupportsString
+function _str(sString) sString.QueryInterface(Components
+ .interfaces.nsISupportsString).data;
+
+var _svuSvc = Components.classes["@sciviews.org/svUtils;1"]
+ .getService(Components.interfaces.svIUtils);
+var _obsSvc = Components.classes["@mozilla.org/observer-service;1"]
+ .getService(Components.interfaces.nsIObserverService);
+
+var observer;
+var obsCallback = function() { sv.cmdout.append("test")};
+
+this.__defineGetter__ ('command', function () _svuSvc.lastCommand);
+this.__defineGetter__ ('result', function () _svuSvc.lastResult);
+
+// get list of running R processes
+this.getRProc = function(property) {
+ if (!property) property = "CommandLine";
+ var procList = _svuSvc.getproc(property);
+ proc = [];
+ while(procList.hasMoreElements())
+ proc.push(_str(procList.getNext()));
+ return proc;
+}
+
+// Observer of 'r-command-executed' notification
+function rObserver() this.register();
+rObserver.prototype = {
+ observe: function(subject, topic, data) {
+ //ko.dialogs.alert(topic + ":\r\n" + data);
+ obsCallback(_svuSvc.lastCommand, data);
+ },
+ register: function() {
+ _obsSvc.addObserver(this, "r-command-executed", false);
+ },
+ unregister: function() {
+ _obsSvc.removeObserver(this, "r-command-executed");
+ }
+}
+
+this.removeObserver = function() {
+ observer.unregister();
+ callback = function() {};
+}
+
+// Set callback for executing R command
+this.setObserver = function(callback) {
+ try {
+ _this.removeObserver();
+ } catch(e) {}
+ observer = new rObserver();
+ if (callback) obsCallback = callback;
+}
+
+
+// Evaluate in R
+this.rEval = function(command, callback) {
+ if(callback) _this.setObserver(callback);
+ _svuSvc.execInRBgr(command, 'localhost', 8888);
+}
+
+// TODO: this should use <<<h>>>
+// Evaluate in R quickly - and return result
+this.rEvalQuick = function(command)
+ _svuSvc.execInR(command, 'localhost', 8888);
+
+
+// For debugging purposes only
+this.testRCommand = function(command) {
+ if(!command) command = "sample(LETTERS, 10)";
+ _svuSvc.execInRBgr(command, 'localhost', 8888);
+}
+
+this.testRCommandNotify = function() {
+ _obsSvc.notifyObservers(null, "r-command-executed", "!!!");
+}
+
+}).apply(sv.rnew);
+
+
+// seems to be no problem with encoding (!!?)
+//sv.rnew.testRCommand("cat('pchn¹æ w tê ³ód je¿a i óm skrzyñ fig')")
+
+var rCallback = function(cmd, res) {
+ sv.cmdout.clear();
+ sv.cmdout.append("::>"+ cmd + "\n" + res)
+}
+
+//sv.rnew.rEval("cat(1:10)", ko.dialogs.alert);
+//result = sv.rnew.rEvalQuick("cat(1:10)");
More information about the Sciviews-commits
mailing list