[Sciviews-commits] r380 - in komodo: SciViews-K SciViews-K/components SciViews-K/content/js SciViews-K-dev/content/js

noreply at r-forge.r-project.org noreply at r-forge.r-project.org
Mon Jul 18 17:45:14 CEST 2011


Author: phgrosjean
Date: 2011-07-18 17:45:13 +0200 (Mon, 18 Jul 2011)
New Revision: 380

Added:
   komodo/SciViews-K-dev/content/js/r_new.js
Removed:
   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
   komodo/SciViews-K/content/js/pref-R.js
   komodo/SciViews-K/content/js/prefs.js
   komodo/SciViews-K/content/js/r.js
   komodo/SciViews-K/content/js/sciviews.js
   komodo/SciViews-K/content/js/socket.js
   komodo/SciViews-K/install.rdf
Log:
Cleanup of code for SciViews-K 0.9.22

Modified: komodo/SciViews-K/components/Conscript
===================================================================
--- komodo/SciViews-K/components/Conscript	2011-07-18 13:40:22 UTC (rev 379)
+++ komodo/SciViews-K/components/Conscript	2011-07-18 15:45:13 UTC (rev 380)
@@ -51,4 +51,3 @@
     'havePy2to3',
 );
 $cons->InstallXpcomComponent('koRLinter.py');
-$cons->InstallXpcomComponent('svUtils.py');

Deleted: komodo/SciViews-K/components/svIUtils.idl
===================================================================
--- komodo/SciViews-K/components/svIUtils.idl	2011-07-18 13:40:22 UTC (rev 379)
+++ komodo/SciViews-K/components/svIUtils.idl	2011-07-18 15:45:13 UTC (rev 380)
@@ -1,55 +0,0 @@
-/* ***** 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"
-
-// This is implemented in sv.rnew's JavaScript code.
-[scriptable, uuid(ca1bcf00-394d-11e0-bd69-0002a5d5c51b)]
-interface svIStuffListener: nsISupports {
-    wstring onStuff(in wstring data);
-};
-
-[scriptable, uuid(5f82d460-37b6-11e0-b897-0002a5d5c51b)]
-interface svIUtils : nsISupports {
-	wstring execFun(in svIStuffListener stuffLlistener);
-	void execFunInBgr(in svIStuffListener requestHandler);
-    nsISimpleEnumerator getproc(in string propertyName);
-	wstring	execInR(in wstring command, in string host, in long port, in string mode);
-	void	execInRBgr(in wstring command, in string host, in long port, in string mode);
-	boolean startSocketServer(in string host, in long port, in svIStuffListener requestHandler);
-	void stopSocketServer();
-	attribute wstring lastCommand;
-	attribute wstring lastResult;
-	attribute wstring id;
-};

Deleted: komodo/SciViews-K/components/svUtils.py
===================================================================
--- komodo/SciViews-K/components/svUtils.py	2011-07-18 13:40:22 UTC (rev 379)
+++ komodo/SciViews-K/components/svUtils.py	2011-07-18 15:45:13 UTC (rev 380)
@@ -1,256 +0,0 @@
-#!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 string
-from xpcom.server.enumerator import SimpleEnumerator
-import socket
-import threading
-import logging
-log = logging.getLogger('svUtils')
-#log.setLevel(logging.INFO)
-log.setLevel(logging.DEBUG)
-
-
-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''
-		self.id = 'svpy'
-		self.runServer = False
-		self.serverIsUp = False
-		pass
-
-
-	def execFun(self, stuffLlistener):
-		listenerProxy = getProxyForObject(1,
-			components.interfaces.svIStuffListener,
-			stuffLlistener, PROXY_ALWAYS | PROXY_SYNC)
-		ret = listenerProxy.onStuff("test 123")
-		return ret
-
-	def execFunInBgr(self, requestHandler):
-		t = threading.Thread(target=self._doExecFn, kwargs={
-			'requestHandler': requestHandler
-			})
-		t.start()
-
-	def _doExecFn(self, requestHandler):
-		listenerProxy = getProxyForObject(1,
-			components.interfaces.svIStuffListener,
-			requestHandler, PROXY_ALWAYS | PROXY_SYNC)
-		listenerProxy.onStuff("test 12345...")
-
-	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, return several properties at a time
-		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_(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, mode):
-		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-		s.settimeout(.5) # increase if not localhost
-		try:
-			s.connect((host, port))
-		except BaseException, e:
-			return unicode(e.args[0]);
-
-		# TODO: allow for <<<h>>>
-		s.send('<<<id=' + self.id + '>>><<<' + mode + '>>>' + command)
-		s.shutdown(socket.SHUT_WR) # does not work without shutdown, why?
-		result = ''
-		while True:
-			data = s.recv(1024)
-			if not data: break
-			result += data
-		s.close()
-		return unicode(result)
-
-	def execInRBgr(self, command, host, port, mode):
-		t = threading.Thread(target=self.rconnect, args=(command, host, port, mode))
-		#t.daemon = True
-		t.start()
-
-	def rconnect(self, command, host, port, mode):
-		self.lastCommand = unicode(command)
-		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-		s.connect((host, port))
-		s.settimeout(None)
-		s.send('<<<id=' + self.id + '>>><<<' + mode + '>>>' + 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
-		s.close()
-		self.lastResult = unicode(result)
-		self._proxiedObsSvc.notifyObservers(None, 'r-command-executed', result)
-		#try:
-		#self._proxiedObsSvc.notifyObservers(None, 'r-command-executed', result)
-		#except Exception:
-			#log.exception("r-command-executed notification failed")
-
-	def startSocketServer(self, host, port, requestHandler):
-		# TODO: do not run two! use semaphore
-		if(self.serverIsUp): return False
-		self.runServer = True
-		t = threading.Thread(target=self._SocketServer, kwargs={
-			'host': host,
-			'port': port,
-			'requestHandler': requestHandler
-			})
-		t.start()
-		log.debug('Started socket server at port %d' % port)
-		return True
-
-	def stopSocketServer(self):
-		self.runServer = False
-		log.debug('Told socket server to stop')
-
-
-	def _SocketServer(self, host, port, requestHandler):
-		# requestHandler is a Javascript object with component 'onStuff'
-		# which is a function accepting one argument (string), and returning
-		# a string
-		requestHandlerProxy = getProxyForObject(1,
-			components.interfaces.svIStuffListener,
-			requestHandler, PROXY_ALWAYS | PROXY_SYNC)
-		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-		s.settimeout(5)
-		try:
-			s.bind((host, port))
-		except Exception, e:
-			log.exception(e)
-			return
-		self.serverIsUp = True
-		s.listen(1)
-		log.debug('Socket server listening at %d' % port)
-		count = 0
-		connected = False
-		while self.runServer:
-			while self.runServer:
-				connected = False
-				try:
-					conn, addr = s.accept()
-					connected = True
-					conn.setblocking(1)
-					count += 1
-					break
-				except Exception, e:
-					#print(e)
-					continue
-			if not connected: continue
-			data_all = ''
-			while connected:
-				log.debug('Connected by %s : %d' % addr)
-				data = conn.recv(1024)
-				data_all += data
-				if (not data) or (data[-1] == '\n'): break
-			#print "Sending:", data_all + "."
-			## Process data here
-			#result = data_all # echo request
-			#unicode(data_all) ?????
-			try:
-				result = requestHandlerProxy.onStuff(data_all)
-			except BaseException, e:
-				result = e.args[0]
-				log.debug('JS request exception: %s' % result)
-			if (result == None): conn.send('\n')
-			else: conn.send(result + '\n')
-			conn.shutdown(socket.SHUT_RDWR)
-			conn.close()
-			log.debug('conn closed')
-		#s.shutdown(socket.SHUT_RDWR) #  Is it necessarry?
-		s.close()
-		self.serverIsUp = False
-		log.debug("Exiting after %d connections" % count)
-		pass
-
-
-#    conn.setblocking(1)
-#  File "<string>", line 1, in setblocking
-#  File "/home/kamil/Komodo-Edit-6/lib/python/lib/python2.6/socket.py", line 165, in _dummy
-#    raise error(EBADF, 'Bad file descriptor')
-#error: [Errno 9] Bad file descriptor
-
-
-	#def Run(self, command, env, console):
-	#	pass
-	#
-	#def _WaitNotifyAndCleanUp(self, child, command, scriptFileName=None):

Modified: komodo/SciViews-K/content/js/pref-R.js
===================================================================
--- komodo/SciViews-K/content/js/pref-R.js	2011-07-18 13:40:22 UTC (rev 379)
+++ komodo/SciViews-K/content/js/pref-R.js	2011-07-18 15:45:13 UTC (rev 380)
@@ -216,14 +216,16 @@
 function OnPreferencePageOK(prefset) {
 	prefset = parent.hPrefWindow.prefset;
 
-	//prefset.setStringPref("svRDefaultInterpreter",
-	//document.getElementById("svRDefaultInterpreter").value);
-	//prefset.setStringPref("svRApplication",
-	//	document.getElementById('svRApplication')
-	//	.selectedItem.getAttribute("value"));
+	// PhG: why was this commented out? Causes problems on the Mac!!!
+	prefset.setStringPref("svRDefaultInterpreter",
+	document.getElementById("svRDefaultInterpreter").value);
+	prefset.setStringPref("svRApplication",
+		document.getElementById('svRApplication')
+		.selectedItem.getAttribute("value"));
 
-	//prefset.setStringPref("svRApplicationId",
-	//	document.getElementById('svRApplication').selectedItem.id);
+	prefset.setStringPref("svRApplicationId",
+		document.getElementById('svRApplication').selectedItem.id);
+	// PhG: was commented out unitl here...
 
 
 	var outDec = document.getElementById('r.csv.dec').value;

Modified: komodo/SciViews-K/content/js/prefs.js
===================================================================
--- komodo/SciViews-K/content/js/prefs.js	2011-07-18 13:40:22 UTC (rev 379)
+++ komodo/SciViews-K/content/js/prefs.js	2011-07-18 15:45:13 UTC (rev 380)
@@ -19,7 +19,7 @@
 // sv.prefs.defaults[preferenceName] = preferenceValue
 sv.prefs.defaults = {
 	"sciviews.server.socket": "7052",
-	"sciviews.client.type": "socket", // temporarily changed from "http"
+	"sciviews.client.type": "socket",
 	"sciviews.client.socket": "8888",
 	"sciviews.client.id": "SciViewsK",
 	"sciviews.server.host": "127.0.0.1",
@@ -135,21 +135,20 @@
 //TODO: Rework this with respect to Mac and R.app
 // Default R interpreter Id: use a reasonable default, given the platform
 if (navigator.platform.indexOf("Win") === 0) {
-	sv.prefs.setString("svRApplication", "r-gui", !sv.prefs.getString("svRApplication", "r-gui"));
+	sv.prefs.setString("svRApplication", "r-gui", false);
 	if (!svRDefaultInterpreter)
 		svRDefaultInterpreter = sv.tools.file.whereIs("Rgui");
 } else {
-	sv.prefs.setString("svRApplication", "r-terminal", !sv.prefs.getString("svRApplication", "r-gui"));
+	sv.prefs.setString("svRApplication", "r-terminal", false);
 	if (!svRDefaultInterpreter)
 		svRDefaultInterpreter = sv.tools.file.whereIs("R");
 }
-sv.prefs.setString("svRDefaultInterpreter", svRDefaultInterpreter, 
-	!sv.prefs.getString("svRDefaultInterpreter", "r-gui"));
+// PhG: this must disappear: it causes trouble on Mac and with HTTP server!!!
+//sv.prefs.setString("svRDefaultInterpreter", svRDefaultInterpreter, 
+//	!sv.prefs.getString("svRDefaultInterpreter", "r-gui"));
+//sv.prefs.setString("sciviews.client.type", "socket", true); // DEBUG: Force "socket"
 
 
-sv.prefs.setString("sciviews.client.type", "socket", true); // DEBUG: Force "socket"
-
-
 // This is required by sv.helpContext() for attaching help to snippets (hack!)
 // Create empty preference sets to be used with snippet help system hack
 // [[%pref:R-help:value]] which displays nothing when the snippet is used

Modified: komodo/SciViews-K/content/js/r.js
===================================================================
--- komodo/SciViews-K/content/js/r.js	2011-07-18 13:40:22 UTC (rev 379)
+++ komodo/SciViews-K/content/js/r.js	2011-07-18 15:45:13 UTC (rev 380)
@@ -179,6 +179,7 @@
 	// For now, use the command output pane
 	if (command) { // This is a R command
 		if (partial) {
+			sv.cmdout.append(text, newline);
 			sv.cmdout.message("R waits for more input...", 0, true);
 		} else { // This is a new command
 			sv.cmdout.clear();
@@ -191,8 +192,6 @@
 		if (!partial) sv.cmdout.message("R is ready!", 0, false);
 		sv.cmdout.append(text, newline);
 	}
-	// PhG: echo of commands is now done by the server, but still needed hereabove
-	//sv.cmdout.append(text, newline);
 }
 
 // Evaluate code in R

Deleted: komodo/SciViews-K/content/js/r_new.js
===================================================================
--- komodo/SciViews-K/content/js/r_new.js	2011-07-18 13:40:22 UTC (rev 379)
+++ komodo/SciViews-K/content/js/r_new.js	2011-07-18 15:45:13 UTC (rev 380)
@@ -1,212 +0,0 @@
-//{  }
-
-// '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'
-//.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
-//.startSocketServer(requestHandler) - optional 'requestHandler' is a function that
-//		handles the received data and returns a string
-//.stopSocketServer()
-//.testRAvailability(checkProc) - test whether R is available, check connection and
-//		optionally look up running processes
-//Debugging functions:
-//.testRCommand(command)
-//.testRCommandNotify(chunk)
-//.enumObservers()
-//Functions below should not be called directy by the user.
-//	they will become private later
-//*.setObserver(callback, topic) set callback function for R command
-//*.removeObserver
-
-
-try { // in case we inject the script more then one time
-	sv.rnew.removeObserver();
-} catch(e) {}
-
-
-sv.rnew = {};
-
-(function() {
-	var _this = this;
-	this.port = 8888;
-	this.serverPort = 7052;
-	this.host = 'localhost';
-
-// 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 observers = {};
-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(topic, callback) this.register(topic, callback);
-rObserver.prototype = {
-	observe: function(subject, topic, data) {
-		//ko.dialogs.alert(topic + ":\r\n" + data);
-		this.callback(_svuSvc.lastCommand, data);
-	},
-	register: function(topic, callback) {
-		if(callback) this.callback = callback;
-		this.topic = topic;
-		_obsSvc.addObserver(this, topic, false);
-	},
-	unregister: function() {
-		_obsSvc.removeObserver(this, this.topic);
-	},
-
-	topic: null,
-	callback: function(cmd, data) ko.dialogs.alert(cmd, data)
-}
-
-this.removeObserver = function(topic) {
-	if (!topic)	for (var i in observers) {
-		observers[i].unregister();
-		delete observers[i];
-	}
-	else {
-		observers[topic].unregister();
-		delete observers[topic];
-	}
-}
-
-// Set callback for executing R command
-this.setObserver = function(callback, topic) {
-	if(!topic) topic = "r-command-executed";
-
-	try {
-		_this.removeObserver(topic);
-	} catch(e) {}
-	observers[topic] = new rObserver(topic, callback);
-}
-
-this.enumObservers = function() {
-	var ret = [];
-	for (var i in observers) ret.push(observers[i]);
-	return ret;
-}
-
-// Evaluate in R
-this.rEval = function(command, callback, hidden) {
-	if(callback) _this.setObserver(callback, "r-command-executed");
-	_svuSvc.execInRBgr(command, _this.host, _this.port, hidden? "h" : "e");
-}
-
-// TODO: this should use <<<h>>>
-// Evaluate in R quickly - and return result
-this.rEvalQuick = function(command)
-	_svuSvc.execInR(command, _this.host, _this.port, "h");
-
-
-// For debugging purposes only
-this.testRCommand = function(command) {
-	if(!command) command = "sample(LETTERS, 10)";
-	_svuSvc.execInRBgr(command, _this.host, _this.port, "e");
-}
-
-this.testRCommandNotify = function(chunk) {
-	topic = "r-command" + (chunk? "chunk" : "executed");
-	_obsSvc.notifyObservers(null, topic, "You are notified. {" + topic + "}");
-}
-
-var rCallback = function(cmd, res) {
-	//sv.cmdout.clear();
-	sv.cmdout.append("::>"+ cmd + ": END")
-}
-
-var rCallbackChunk = function(cmd, res) {
-	sv.cmdout.append("\n<++CHUNK++>\n"+ res, false)
-}
-
-this.testRAvailability = function(checkProc) {
-	var result = _this.rEvalQuick("cat(1)").trim();
-	var connectionUp = result == "1";
-	var rProcess = checkProc? _this.getRProc() : undefined;
-	var rProcessCount = (rProcess == undefined)? -1 : rProcess.length;
-	ret = '';
-	if(!connectionUp) {
-		ret += "Cannot connect to R";
-		if (rProcessCount > 0) {
-			ret += ", but there " + ((rProcessCount > 1)? "are " + rProcessCount
-				+ " R processes": "is one R process") + " running.";
-			result += "\n\nR processes currently running:\n" + rProcess.join("\n");
-		} else if (rProcessCount == 0) {
-			ret += ",  R is not running.";
-		}
-	} else {
-		result = null;
-		ret += "Connection with R successful.";
-	}
-	//ko.dialogs.alert(ret, result, "R connection test");
-	sv.cmdout.append("R connection test:\n" + ret + "\n"  + result);
-	return connectionUp;
-}
-
-_this.setObserver(rCallbackChunk, "r-command-chunk");
-_this.setObserver(rCallback, "r-command-executed");
-
-var defaultRequestHandler = function(str) {
-	str = str.trim();
-	//sv.cmdout.append(str);
-	try {
-		if (str.indexOf("<<<js>>>") == 0)
-			return eval(str.substring(8));
-		 else if(str.indexOf("<<<rjsonp>>>") == 0)
-			return sv.rjson.eval(str.substring(12));
-	} catch(e) {
-		return e.message;
-	}
-	sv.cmdout.append(str);
-	return "Received: [" + str + "]"; // echo
-}
-
-
-this.startSocketServer = function(requestHandler) {
-	_this.host = sv.prefs.getString("sciviews.server.host");
-	_this.serverPort = parseInt(sv.prefs.getString("sciviews.server.socket"));
-
-	if(!requestHandler) requestHandler = defaultRequestHandler;
-	return _svuSvc.startSocketServer(_this.host, _this.serverPort, {onStuff: requestHandler});
-}
-
-this.stopSocketServer = function() _svuSvc.stopSocketServer();
-
-addEventListener("load", function() {
-	sv.command.updateRStatus(_this.testRAvailability(false));
-	_this.startSocketServer();
-}, false);
-
-
-}).apply(sv.rnew);
-
-
-// seems to be no problem with encoding (!!?)
-//sv.rnew.testRCommand("cat('pchn¹æ w tê ³ódŸ je¿a i óœm skrzyñ fig')") // Note this is CP1250 encoding
-
-
-//sv.rnew.rEval("cat(1:10)", ko.dialogs.alert);
-//result = sv.rnew.rEvalQuick("cat(1:10)");

Modified: komodo/SciViews-K/content/js/sciviews.js
===================================================================
--- komodo/SciViews-K/content/js/sciviews.js	2011-07-18 13:40:22 UTC (rev 379)
+++ komodo/SciViews-K/content/js/sciviews.js	2011-07-18 15:45:13 UTC (rev 380)
@@ -704,6 +704,18 @@
 
 // Clear text in the Output Command pane
 this.clear = function (all) {
+	// PhG: this was in old code... but since new code does not work on Win Vista
+	// I reinject this to see if it solves the problem!
+	try {
+		var runout = ko.run.output;
+		// Make sure the command output window is visible
+		runout.show(window, false);
+		// Make sure we're showing the output pane
+		var deckWidget = document.getElementById("runoutput-deck");
+		if (deckWidget.getAttribute("selectedIndex") != 0)
+			runout.toggleView();
+	} finally { }
+		
 	if (!scimoz) _init();
 	if (all) _this.message();
 	var readOnly = scimoz.readOnly;
@@ -713,8 +725,8 @@
 	} finally {
 		scimoz.readOnly = readOnly;
 	}
+}
 
-}
 // Display message on the status bar (default) or command output bar
 this.message = function (msg, timeout, highlight) {
 	document.getElementById('output_tabpanels').selectedIndex = 0;
@@ -729,12 +741,9 @@
 		.setTimeout("sv.cmdout.message('', 0);", timeout);
 }
 
-
 }).apply(sv.cmdout);
 
 
-
-
 //// Logging management ////////////////////////////////////////////////////////
 if (typeof(sv.log) == 'undefined') sv.log = {};
 

Modified: komodo/SciViews-K/content/js/socket.js
===================================================================
--- komodo/SciViews-K/content/js/socket.js	2011-07-18 13:40:22 UTC (rev 379)
+++ komodo/SciViews-K/content/js/socket.js	2011-07-18 15:45:13 UTC (rev 380)
@@ -238,7 +238,14 @@
 	return(null);
 }
 
-this.rClient = this.rClientSocket; // default client type
+this.rClient = function (host, port, cmd, listener, echo, procname) {
+	if (sv.clientType == "socket") {
+		res = this.rClientSocket(host, port, cmd, listener, echo, procname);
+	} else {
+		res = this.rClientHttp(host, port, cmd, listener, echo, procname)
+	}
+	return(res);
+}
 
 // TODO: use this on preference change "sciviews.client.type"
 this.setSocketType = function (type) {
@@ -341,7 +348,7 @@
 // TODO: add the current working directory and report WD changes from R automagically
 this.rUpdate = function () {
 	// Make sure that dec and sep are correctly set in R
-	this.rCommand('<<<h>>>options(' +
+	this.rCommand('<<<H>>>options(' +
 		'OutDec = "' + sv.prefs.getString("r.csv.dec", ".") +
 		'", OutSep = "' + sv.prefs.getString("r.csv.sep", ",") +
 		'"); invisible(guiRefresh(force = TRUE)); ' +

Modified: komodo/SciViews-K/install.rdf
===================================================================
--- komodo/SciViews-K/install.rdf	2011-07-18 13:40:22 UTC (rev 379)
+++ komodo/SciViews-K/install.rdf	2011-07-18 15:45:13 UTC (rev 380)
@@ -4,7 +4,7 @@
     <Description about="urn:mozilla:install-manifest">
         <em:id>sciviewsk at sciviews.org</em:id>
         <em:name>SciViews-K</em:name>
-        <em:version>0.9.21</em:version>
+        <em:version>0.9.22</em:version>
         <em:description>Edit R (http://www.r-project.org) code with Komodo</em:description>
         <em:creator>Philippe Grosjean</em:creator>
         <em:contributor>Romain Francois</em:contributor>

Added: komodo/SciViews-K-dev/content/js/r_new.js
===================================================================
--- komodo/SciViews-K-dev/content/js/r_new.js	                        (rev 0)
+++ komodo/SciViews-K-dev/content/js/r_new.js	2011-07-18 15:45:13 UTC (rev 380)
@@ -0,0 +1,212 @@
+//{  }
+
+// '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'
+//.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
+//.startSocketServer(requestHandler) - optional 'requestHandler' is a function that
+//		handles the received data and returns a string
+//.stopSocketServer()
+//.testRAvailability(checkProc) - test whether R is available, check connection and
+//		optionally look up running processes
+//Debugging functions:
+//.testRCommand(command)
+//.testRCommandNotify(chunk)
+//.enumObservers()
+//Functions below should not be called directy by the user.
+//	they will become private later
+//*.setObserver(callback, topic) set callback function for R command
+//*.removeObserver
+
+
+try { // in case we inject the script more then one time
+	sv.rnew.removeObserver();
+} catch(e) {}
+
+
+sv.rnew = {};
+
+(function() {
+	var _this = this;
+	this.port = 8888;
+	this.serverPort = 7052;
+	this.host = 'localhost';
+
+// 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 observers = {};
+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(topic, callback) this.register(topic, callback);
+rObserver.prototype = {
+	observe: function(subject, topic, data) {
+		//ko.dialogs.alert(topic + ":\r\n" + data);
+		this.callback(_svuSvc.lastCommand, data);
+	},
+	register: function(topic, callback) {
+		if(callback) this.callback = callback;
+		this.topic = topic;
+		_obsSvc.addObserver(this, topic, false);
+	},
+	unregister: function() {
+		_obsSvc.removeObserver(this, this.topic);
+	},
+
+	topic: null,
+	callback: function(cmd, data) ko.dialogs.alert(cmd, data)
+}
+
+this.removeObserver = function(topic) {
+	if (!topic)	for (var i in observers) {
+		observers[i].unregister();
+		delete observers[i];
+	}
+	else {
+		observers[topic].unregister();
+		delete observers[topic];
+	}
+}
+
+// Set callback for executing R command
+this.setObserver = function(callback, topic) {
+	if(!topic) topic = "r-command-executed";
+
+	try {
+		_this.removeObserver(topic);
+	} catch(e) {}
+	observers[topic] = new rObserver(topic, callback);
+}
+
+this.enumObservers = function() {
+	var ret = [];
+	for (var i in observers) ret.push(observers[i]);
+	return ret;
+}
+
+// Evaluate in R
+this.rEval = function(command, callback, hidden) {
+	if(callback) _this.setObserver(callback, "r-command-executed");
+	_svuSvc.execInRBgr(command, _this.host, _this.port, hidden? "h" : "e");
+}
+
+// TODO: this should use <<<h>>>
+// Evaluate in R quickly - and return result
+this.rEvalQuick = function(command)
+	_svuSvc.execInR(command, _this.host, _this.port, "h");
+
+
+// For debugging purposes only
+this.testRCommand = function(command) {
+	if(!command) command = "sample(LETTERS, 10)";
+	_svuSvc.execInRBgr(command, _this.host, _this.port, "e");
+}
+
+this.testRCommandNotify = function(chunk) {
+	topic = "r-command" + (chunk? "chunk" : "executed");
+	_obsSvc.notifyObservers(null, topic, "You are notified. {" + topic + "}");
+}
+
+var rCallback = function(cmd, res) {
+	//sv.cmdout.clear();
+	sv.cmdout.append("::>"+ cmd + ": END")
+}
+
+var rCallbackChunk = function(cmd, res) {
+	sv.cmdout.append("\n<++CHUNK++>\n"+ res, false)
+}
+
+this.testRAvailability = function(checkProc) {
+	var result = _this.rEvalQuick("cat(1)").trim();
+	var connectionUp = result == "1";
+	var rProcess = checkProc? _this.getRProc() : undefined;
+	var rProcessCount = (rProcess == undefined)? -1 : rProcess.length;
+	ret = '';
+	if(!connectionUp) {
+		ret += "Cannot connect to R";
+		if (rProcessCount > 0) {
+			ret += ", but there " + ((rProcessCount > 1)? "are " + rProcessCount
+				+ " R processes": "is one R process") + " running.";
+			result += "\n\nR processes currently running:\n" + rProcess.join("\n");
+		} else if (rProcessCount == 0) {
+			ret += ",  R is not running.";
+		}
+	} else {
+		result = null;
+		ret += "Connection with R successful.";
+	}
+	//ko.dialogs.alert(ret, result, "R connection test");
+	sv.cmdout.append("R connection test:\n" + ret + "\n"  + result);
+	return connectionUp;
+}
+
+_this.setObserver(rCallbackChunk, "r-command-chunk");
+_this.setObserver(rCallback, "r-command-executed");
+
+var defaultRequestHandler = function(str) {
+	str = str.trim();
+	//sv.cmdout.append(str);
+	try {
+		if (str.indexOf("<<<js>>>") == 0)
+			return eval(str.substring(8));
+		 else if(str.indexOf("<<<rjsonp>>>") == 0)
+			return sv.rjson.eval(str.substring(12));
+	} catch(e) {
+		return e.message;
+	}
+	sv.cmdout.append(str);
+	return "Received: [" + str + "]"; // echo
+}
+
+
+this.startSocketServer = function(requestHandler) {
+	_this.host = sv.prefs.getString("sciviews.server.host");
+	_this.serverPort = parseInt(sv.prefs.getString("sciviews.server.socket"));
+
+	if(!requestHandler) requestHandler = defaultRequestHandler;
+	return _svuSvc.startSocketServer(_this.host, _this.serverPort, {onStuff: requestHandler});
+}
+
+this.stopSocketServer = function() _svuSvc.stopSocketServer();
+
+addEventListener("load", function() {
+	sv.command.updateRStatus(_this.testRAvailability(false));
+	_this.startSocketServer();
+}, false);
+
+
+}).apply(sv.rnew);
+
+
+// seems to be no problem with encoding (!!?)
+//sv.rnew.testRCommand("cat('pchn¹æ w tê ³ódŸ je¿a i óœm skrzyñ fig')") // Note this is CP1250 encoding
+
+
+//sv.rnew.rEval("cat(1:10)", ko.dialogs.alert);
+//result = sv.rnew.rEvalQuick("cat(1:10)");



More information about the Sciviews-commits mailing list