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

noreply at r-forge.r-project.org noreply at r-forge.r-project.org
Mon Aug 8 22:49:09 CEST 2011


Author: prezez
Date: 2011-08-08 22:49:09 +0200 (Mon, 08 Aug 2011)
New Revision: 384

Modified:
   komodo/SciViews-K-dev/components/koRLinter.py
   komodo/SciViews-K-dev/components/svIUtils.idl
   komodo/SciViews-K-dev/components/svUtils.py
   komodo/SciViews-K-dev/content/RPkgManager.xul
   komodo/SciViews-K-dev/content/js/commands.js
   komodo/SciViews-K-dev/content/js/pref-R.js
   komodo/SciViews-K-dev/content/js/r.js
   komodo/SciViews-K-dev/content/js/rconnection.js
   komodo/SciViews-K-dev/content/js/robjects.js
   komodo/SciViews-K-dev/content/js/sciviews.js
   komodo/SciViews-K-dev/install.rdf
Log:
SciViews-K dev version: many small changes


Modified: komodo/SciViews-K-dev/components/koRLinter.py
===================================================================
--- komodo/SciViews-K-dev/components/koRLinter.py	2011-08-08 20:47:13 UTC (rev 383)
+++ komodo/SciViews-K-dev/components/koRLinter.py	2011-08-08 20:49:09 UTC (rev 384)
@@ -50,6 +50,26 @@
 log = logging.getLogger('RLinter')
 log.setLevel(logging.DEBUG)
 
+
+
+#ss = s * 5000
+#t0 = time.clock()
+#for n in range(100):
+#    ss.replace("\x03", "").replace("\x02", "")
+#t1 = time.clock() - t0
+#print(t1)
+##0.19073865575
+#ss = s * 5000
+#pat = re.compile('[\x02\x03]')
+#t0 = time.clock()
+#for n in range(100):
+#    pat.sub("", ss)
+#t1 = time.clock() - t0
+#print(t1)
+##0.836379887645
+
+
+
 class KoRLinter:
     _com_interfaces_ = [components.interfaces.koILinter]
     _reg_desc_ = "Komodo R Linter"
@@ -84,14 +104,15 @@
         except Exception, e:
             log.exception(e)
         try:
-            lines = self.sv_utils.execInR(command, "h").rstrip()
+            lines = self.sv_utils.execInR(command, "h", 1.5).rstrip() \
+                .replace('\x03', '').replace('\x02', '')
             if lines == 'timed out':
                 raise ServerException(nsError.NS_ERROR_NOT_AVAILABLE)
 
-            log.debug("lint: " + lines)
+            log.debug('lint: ' + lines)
             ma = self.pattern.match(lines)
             if (ma):
-                lineNo = int(ma.group("line"))
+                lineNo = int(ma.group('line'))
                 datalines = re.split('\r\n|\r|\n', request.content, lineNo) # must not to be encoded
                 columnNo = int(ma.group("col"))
                 description = ma.group("descr")

Modified: komodo/SciViews-K-dev/components/svIUtils.idl
===================================================================
--- komodo/SciViews-K-dev/components/svIUtils.idl	2011-08-08 20:47:13 UTC (rev 383)
+++ komodo/SciViews-K-dev/components/svIUtils.idl	2011-08-08 20:49:09 UTC (rev 384)
@@ -46,6 +46,9 @@
     readonly attribute ACString commandId;
     readonly attribute AUTF8String command;
     readonly attribute ACString mode;
+	attribute AUTF8String message;
+	attribute AUTF8String result;
+	ACString styledResult();
 };
 
 
@@ -59,9 +62,12 @@
 	void setSocketInfo(in ACString host, in long port, in boolean outgoing);
 	readonly attribute AUTF8String lastCommand;
 	readonly attribute AUTF8String lastResult;
-	attribute ACString id;
+	readonly attribute AUTF8String lastMessage;
+	#attribute ACString id;
 	boolean serverIsUp();
 	wstring pushLeft(in AUTF8String text, in ACString eol, in long indent, in long tabwidth);
+	ACString uid();
+	ACString makeStyledText(in AUTF8String text);
 
     void escape();
     void calltip(in AUTF8String text);

Modified: komodo/SciViews-K-dev/components/svUtils.py
===================================================================
--- komodo/SciViews-K-dev/components/svUtils.py	2011-08-08 20:47:13 UTC (rev 383)
+++ komodo/SciViews-K-dev/components/svUtils.py	2011-08-08 20:49:09 UTC (rev 384)
@@ -41,12 +41,29 @@
 from xpcom.server.enumerator import SimpleEnumerator
 import socket
 import threading
+import json
+from uuid import uuid1
 import logging
 log = logging.getLogger('svUtils')
 #log.setLevel(logging.INFO)
 log.setLevel(logging.DEBUG)
 
 
+def _makeStyledText(text, styles = {chr(2): chr(0), chr(3): chr(23)},
+    curStyle = chr(0)):
+    ctrlChars = styles.keys()
+    text8 = text.encode('utf-8')
+    #curStyle = styles.values()[0]
+    ret = u''
+    for ch in text8:
+        if ch in ctrlChars:
+            curStyle = styles[ch]
+            log.debug(ord(ch))
+        else:
+            ret += ch + curStyle
+    return ret
+
+
 class svUtils:
     _com_interfaces_ = [components.interfaces.svIUtils]
     _reg_desc_ = "SciViews-K utilities"
@@ -63,20 +80,31 @@
 
         self.lastCommand = u''
         self.lastResult = u''
-        self.id = 'sv'
+        self.lastMessage = u''
         self.runServer = False
-        self.socketOut = ('localhost', 8888)
-        self.socketIn = ('localhost', 7777)
+        self.socketOut = ('localhost', 8888L)
+        self.socketIn = ('localhost', 7777L)
         self.serverConn = None
+        #self.myUID = uuid1().hex
+        #self.id = 'sv'
         pass
 
     class _CommandInfo:
         _com_interfaces_ = components.interfaces.svICommandInfo
-        def __init__(self, cmd_id, cmd, mode):
+        def __init__(self, cmd_id, cmd, mode, message = '', result = ''):
             self.commandId = cmd_id
             self.command = cmd
             self.mode = mode
+            self.message = message
+            self.result = result
+        def styledResult(self):
+            return _makeStyledText(self.result)
 
+
+    def makeStyledText(self, text):
+        return _makeStyledText(text)
+
+
     def setSocketInfo(self, host, port, outgoing):
         log.debug("setSocketInfo (%s): %s:%d" % ('outgoing' if outgoing else 'incoming', host, port))
         if outgoing: self.socketOut = (host, port)
@@ -123,7 +151,7 @@
         return SimpleEnumerator(ret)
 
     def execInR(self, command, mode, timeout = .5):
-        return self.rconnect(command, mode, False, timeout, "")
+        return self.rconnect(command, mode, False, timeout, self.uid())
 
     def execInRBgr(self, command, mode, uid):
         log.debug("execInRBgr: %s..." % command[0:10])
@@ -132,45 +160,100 @@
         t.start()
 
     def rconnect(self, command, mode, notify, timeout, uid):
-        pretty_command = self.pushLeft(command, indent=3, eol='\n', tabwidth=4)[3:]
+        pretty_command = self.pushLeft(command, indent=3L, eol='\n', tabwidth=4)[3:]
         self.lastCommand = unicode(command)
         ssLastCmd = self._asSString(command)
         log.debug("rconnect: %s... (%d)" % (command[0:10], notify))
 
+        modeArr = mode.split(' ')
+        useJSON = modeArr.count('json')
+
         s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         s.settimeout(timeout)
         try: s.connect(self.socketOut)
         except Exception, e: return unicode(e.args[0])
+
+        cmdInfo = self._CommandInfo(uid, pretty_command, mode, 'Not ready')
+
+        #wrappedCmdInfo = WrapObject(cmdInfo, components.interfaces.svICommandInfo)
         if notify:
-            cmdInfo = WrapObject(self._CommandInfo(uid, pretty_command, mode),
-                                 components.interfaces.svICommandInfo)
-            self._proxiedObsSvc.notifyObservers(cmdInfo, 'r-command-sent', None)
-        command = '<<<id=' + self.id + '>>><<<' + mode + '>>>' + \
-            re.sub("(\r?\n|\r)", '<<<n>>>', command)
-        s.send(command)
-        s.shutdown(socket.SHUT_WR) # does not work without shutdown, why?
+            self._proxiedObsSvc.notifyObservers(
+                WrapObject(cmdInfo, components.interfaces.svICommandInfo),
+                'r-command-sent', None)
+
+
+        rMode = 'h' if modeArr.count('h') else 'e'
+
+        if useJSON:
+            command = '\x01' \
+                + rMode \
+                + '<' + uid + '>' \
+                + command.replace("\\", "\\\\"). \
+                replace("\n", "\\n").replace("\r", "\\r").replace("\f", "\\f")
+        else:
+            command = '<<<id=' + uid + '>>><<<' + mode + '>>>' + \
+                re.sub("(\r?\n|\r)", '<<<n>>>', command)
+            #command.replace(os.linesep,  '<<<n>>>')
+        s.send(command + os.linesep)
+        ## SOLVED: command must end with newline
+        ## TODO: replace all newlines by R
+        s.shutdown(socket.SHUT_WR)
         result = u''
         try:
             while True:
-                data = s.recv(1024)
+                data = s.recv(1024L)
                 if not data: break
                 if notify:
-                    self._proxiedObsSvc.notifyObservers(cmdInfo, 'r-command-chunk', data)
+                    #self._proxiedObsSvc.notifyObservers(cmdInfo, 'r-command-chunk', data)
+                    self._proxiedObsSvc.notifyObservers(
+                        WrapObject(cmdInfo, components.interfaces.svICommandInfo),
+                        'r-command-chunk', data)
                 result += unicode(data)
         except Exception, e:
             log.debug(e)
             pass
         s.close()
         result = result.rstrip()
-        self.lastResult = result
+        message = ''
+        if useJSON:
+            # Fix bad JSON: R escapes nonprintable characters as octal numbers
+            # (\OOO), but json apparently needs unicode notation (\uHHHH).
+            result = re.sub('(?<=\\\\)[0-9]{3}', lambda x: ("u%04x" % int(x.group(0), 8)), result)
+            try:
+                resultObj = json.loads(result)
+                if(isinstance(resultObj, dict)):
+                    if (resultObj.has_key('message')): message = resultObj['message']
+                    if (resultObj.has_key('result')):
+                        if isinstance(resultObj['result'], list):
+                            result = os.linesep.join(resultObj['result'])
+                        else: # isinstance(x, unicode)
+                            result = resultObj['result']
+                            #log.debug(type(result)) # <-- should be: <type 'unicode'>
+                            #log.debug(result)
+                    cmdInfo.message = unicode(message)
+                    cmdInfo.result = unicode(result)
+
+            except Exception, e:
+                log.debug(e)
+
         if notify:
-            self._proxiedObsSvc.notifyObservers(cmdInfo, 'r-command-executed',
-                                                result)
+
+            #self._proxiedObsSvc.notifyObservers(cmdInfo, 'r-command-executed',
+            #                                    result)
+
+            self._proxiedObsSvc.notifyObservers(
+                WrapObject(cmdInfo, components.interfaces.svICommandInfo),
+                'r-command-executed',
+                result)
+
             log.debug("rconnect notify: %s..." % result[0:10])
             return
         log.debug("rconnect return: %s..." % result[0:10])
-        return result
+        self.lastMessage = message
+        self.lastResult = result
+        return unicode(result)
 
+
 #  File "components\svUtils.py", line 126, in execInR
 #    return self.rconnect(command, mode, False, .5, "")
 #  File "components\svUtils.py", line 153, in rconnect
@@ -179,6 +262,7 @@
 
     def __del__(self):
         try:
+            log.debug("destructor called: closing server")
             self.serverConn.close()
         except:
             pass
@@ -193,9 +277,9 @@
     def startSocketServer(self, requestHandler):
         if(self.serverIsUp()): return -1L
         self.runServer = True
-        host = self.socketIn[0]
-        port = self.socketIn[1]
-        if(port > 70000): port = 10000
+        host = self.socketIn[0L]
+        port = self.socketIn[1L]
+        if(port > 70000L): port = 10000L
         port_max = port + 32L
         while port < port_max:
             try:
@@ -231,7 +315,7 @@
         # requestHandler is a Javascript object with component 'onStuff'
         # which is a function accepting one argument (string), and returning
         # a string
-        requestHandlerProxy = getProxyForObject(1,
+        requestHandlerProxy = getProxyForObject(1L,
             components.interfaces.svIStuffListener,
             requestHandler, PROXY_ALWAYS | PROXY_SYNC)
         try:
@@ -247,7 +331,7 @@
                         connected = True
                         conn.setblocking(1)
                         self.serverConn.settimeout(10)
-                        count += 1
+                        count += 1L
                         break
                     except Exception: continue
                 if not connected: continue
@@ -255,7 +339,7 @@
                 try:
                     while connected:
                         log.debug('Connected by %s : %d' % addr)
-                        data = conn.recv(1024)  # TODO: error: [Errno 10054]
+                        data = conn.recv(1024L)  # TODO: error: [Errno 10054]
                         data_all += data
                         if (not data) or (data[-1] == '\n'): break
                 except Exception, e:
@@ -279,7 +363,11 @@
         self.stopSocketServer()
         #self.serverConn.close()
         log.debug("Exiting after %d connections" % count)
-        self._proxiedObsSvc.notifyObservers(None, 'r-server-stopped', None)
+        try:
+            self._proxiedObsSvc.notifyObservers(None, 'r-server-stopped', None)
+        except Exception, e:
+            log.debug(e)
+            pass
         pass
 
     #import string, re, os, sys
@@ -287,7 +375,7 @@
         text = text.lstrip("\r\n\f")
         if not text: return ''
         re_line = re.compile('(^[\t ]*)(?=\S)(.*$)', re.MULTILINE)
-        if type(indent) != int:
+        if type(indent) in (str, unicode):
            indentstr = indent
            indent = len(indentstr)
         else:
@@ -309,6 +397,9 @@
         text = scimoz.getTextRange(pos_start, pos_end)
         return text
 
+    def uid(self):
+        return(uuid1().hex)
+
     def complete(self, text):
         kvSvc = components.classes["@activestate.com/koViewService;1"] \
             .getService(components.interfaces.koIViewService)
@@ -320,7 +411,8 @@
         if not text.strip(): return
         cmd = 'completion("%s", print=TRUE, types="scintilla", field.sep="?")' \
             % text.replace('"', '\\"')
-        autoCstring = self.execInR(cmd, "h")
+        autoCstring = self.execInR(cmd, "h") \
+            .replace('\x03', '').replace('\x02', '')
 
         if (re.search("^\d+[\r\n]", autoCstring) == None): return
         #scimoz.autoCSeparator = 9
@@ -348,9 +440,10 @@
 
         cmd = 'cat(callTip("%s", location=TRUE, description=TRUE, methods=TRUE, width=80))' \
             % text.replace('"', '\\"')
-        result = self.execInR(cmd, "h")
-        scimoz.callTipCancel();
-        scimoz.callTipShow(scimoz.anchor, result.replace('[\r\n]+', '\n'));
+        result = self.execInR(cmd, "h") \
+            .replace('\x03', '').replace('\x02', '')
+        scimoz.callTipCancel()
+        scimoz.callTipShow(scimoz.anchor, result.replace('[\r\n]+', '\n'))
         return
 
     def escape(self):

Modified: komodo/SciViews-K-dev/content/RPkgManager.xul
===================================================================
--- komodo/SciViews-K-dev/content/RPkgManager.xul	2011-08-08 20:47:13 UTC (rev 383)
+++ komodo/SciViews-K-dev/content/RPkgManager.xul	2011-08-08 20:49:09 UTC (rev 384)
@@ -16,7 +16,6 @@
 
  Contributor(s):
    Kamil Barton
-   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
@@ -346,8 +345,6 @@
 			<radio label="Updates"
 				oncommand="document.getElementById('pkgPanels').selectedIndex = 2;"/>
 		</radiogroup>
-		<spacer flex = "2"/>
-		<button label="Close" onclick="self.close();"/>
 	</hbox>
 
 	<vbox style="font-weight:bold; background-color: #feac01; border: 1px black solid; margin: 2px; padding: 3px;">

Modified: komodo/SciViews-K-dev/content/js/commands.js
===================================================================
--- komodo/SciViews-K-dev/content/js/commands.js	2011-08-08 20:47:13 UTC (rev 383)
+++ komodo/SciViews-K-dev/content/js/commands.js	2011-08-08 20:49:09 UTC (rev 384)
@@ -131,76 +131,24 @@
 		alert("R is closed with code " + exitCode);
 	}
 
-	// Start R
 	this.startR = function () {
-		var exitCode;
-		if (_this.RProcess && _this.RProcess.uuid) try {
-			exitCode = _this.RProcess.wait(0);
-		} catch(e) {
-			var result = ko.dialogs.customButtons("Another instance is running" +
-			"already. Before continuing, you should either quit currently running" +
-			"R or kill its process (if it did not exit cleanly).",
-			['&Kill', '&Quit', "&Cancel"], "Cancel", null, "SciViews-K");
-			switch (result) {
-				case "Kill":
-					try {
-						sv.command.RProcess.kill(true);
-						sv.command.RProcess.wait(3);
-					} catch(e) {}
-					break;
-				case "Quit":
-					sv.r.quit();
-					break;
-				case "Cancel":
-				default:
-					return;
-			}
-			return;
-		}
+		var svfile = sv.tools.file;
+		var svstr = sv.tools.string;
 
-		var cwd = sv.tools.file.path("ProfD", "extensions", "sciviewsk at sciviews.org", "defaults");
-		var cmd = sv.pref.getPref("svRCommand");
+		var rDir = svfile.path("ProfD", "extensions", "sciviewsk at sciviews.org", "R");
 
-		// Remove /defaults/00LOCK if remained after a fail-start
-		try {
-			var lockFile = sv.tools.file.getfile(cwd, "00LOCK");
-			if (lockFile.exists())	lockFile.remove(true);
-		} catch(e) { }
+		svfile.write(svfile.path(rDir, "init.R"),
+			"setwd('"+ svstr.addslashes(sv.pref.getPref("sciviews.session.dir")) + "')\n" +
+			"options(ko.port=" + sv.pref.getPref("sciviews.ko.port", 7052) +
+			", ko.host=\"localhost\")\n"
+			);
 
-		// PhG: on Mac OS X, R.app is not a file, but a dir!!!
-		if (!cmd || (sv.tools.file.exists(sv.tools.string.trim(
-			sv.pref.getPref("svRDefaultInterpreter"))) == sv.tools.file.TYPE_NONE)) {
-			if(ko.dialogs.okCancel(
-			sv.translate("Default R interpreter is not (correctly) set in " +
-				"Preferences. Do you want to do it now?"),
-				"OK", null, "SciViews-K") == "OK") {
-				prefs_doGlobalPrefs("svPrefRItem", true);
-			}
-			return;
-		}
+		var cmd = sv.pref.getPref("svRCommand");
+		var runInConsole = false;
 
 		var isWin = navigator.platform.indexOf("Win") === 0;
 		var id = sv.pref.getPref("svRApplication",
 			isWin? "r-gui" : "r-terminal");
-
-		// runIn = "command-output-window", "new-console",
-		// env strings: "ENV1=fooJ\nENV2=bar"
-		// gPrefSvc.prefs.getStringPref("runEnv");
-		var env = ["koId=" + sv.pref.getPref("sciviews.client.id",
-			"SciViewsK"),
-			"koHost=localhost",
-			"koActivate=FALSE",
-			"Rinitdir=" + sv.pref.getPref("sciviews.session.dir", "~"),
-			//"koType=" + sv.clientType, // Changed value considered only after Komodo restarts!
-			"koType=" + sv.pref.getPref("sciviews.client.type", "socket"), // XXX
-			"koServe=" + sv.pref.getPref("sciviews.r.port", 8888),
-			"koPort=" + sv.pref.getPref("sciviews.ko.port", 7052),
-			"koDebug=" + (sv.log.isAll()? "TRUE" : "FALSE"),
-			"koAppFile=" + sv.tools.file.path("binDir", "komodo" + (isWin? ".exe" : ""))
-		];
-		var runInConsole = false;
-		env.push("Rid=" + id);
-
 		switch (id) {
 			case "r-tk":
 				env.push("Rid=R-tk");
@@ -217,29 +165,27 @@
 			default:
 		}
 
+
 		var runSvc = Components.classes['@activestate.com/koRunService;1']
 			.getService(Components.interfaces.koIRunService);
 
 		var process;
 		if(runInConsole) {
 			// XXX: This does not return a process!
-			runSvc.Run(cmd, cwd, env.join("\n"), runInConsole, null);
+			runSvc.Run(cmd, rDir, "", runInConsole, null);
 			process = null;
 			// Observe = 'status_message'
 			// subject.category = "run_command"
 			// subject.msg = "'%s' returned %s." % (command, retval)
 		} else {
-			process = runSvc.RunAndNotify(cmd, cwd, env.join("\n"), null);
+			process = runSvc.RunAndNotify(cmd, rDir, "", null);
 			// Observe = 'run_terminated'
 			// subject = child
 			// data = command
 			RProcessObserver = new _ProcessObserver(cmd, process, _RterminationCallback);
 		}
-
-		//RProcessObserver = new _ProcessObserver(cmd, process, _RterminationCallback);
 		this.RProcess = process;
 		_this.updateRStatus(true);
-
 	}
 
 	this.updateRStatus = function (running) {
@@ -594,7 +540,6 @@
 									//'cmdset_rApp' commandset being grayed out
 									//at startup...
 		_this.updateRStatus(sv.rconn.testRAvailability(false));
-
 		if(sv.r.running) sv.rbrowser.smartRefresh(true);
 
 	}, 600);
@@ -603,6 +548,13 @@
 	sv.rconn.startSocketServer();
 }
 
+// Just in case, run a clean-up before quitting Komodo:
+function svCleanup() {
+    sv.rconn.stopSocketServer();
+	// ...
+}
+ko.main.addWillCloseHandler(svCleanup);
+
 addEventListener("load", _this.onLoad, false);
 
 }).apply(sv.command);

Modified: komodo/SciViews-K-dev/content/js/pref-R.js
===================================================================
--- komodo/SciViews-K-dev/content/js/pref-R.js	2011-08-08 20:47:13 UTC (rev 383)
+++ komodo/SciViews-K-dev/content/js/pref-R.js	2011-08-08 20:49:09 UTC (rev 384)
@@ -381,7 +381,7 @@
 	}
 
 	var nativeJSON = Components.classes["@mozilla.org/dom/json;1"]
-    .createInstance(Components.interfaces.nsIJSON);
+		.createInstance(Components.interfaces.nsIJSON);
 
 	var jsonFile = svFile.path(localDir, "CRAN_mirrors.json");
 	var alreadyCached = false;

Modified: komodo/SciViews-K-dev/content/js/r.js
===================================================================
--- komodo/SciViews-K-dev/content/js/r.js	2011-08-08 20:47:13 UTC (rev 383)
+++ komodo/SciViews-K-dev/content/js/r.js	2011-08-08 20:49:09 UTC (rev 384)
@@ -87,62 +87,13 @@
 // Define the 'sv.r' namespace
 if (typeof(sv.r) == 'undefined')
 sv.r = {
-	RMinVersion: "2.11.0",	// Minimum version of R required
-//	server: "http", 		// Currently, either 'http' or 'socket'
-	server: "socket", 		// KB: http is still problematic, changed the default
+	RMinVersion: "2.13.0",	// Minimum version of R required
 	sep: ";;",				// Separator used for items
 	running: false			// Indicate if R is currently running
 	// FIXME: before we solve the issue of updating R status
 };
 
-// XXX: Not needed anymore
-// Check where the R executable can be found
-sv.r.application = function (warn) {
-	if (warn === undefined) warn = false;
 
-	// Look for R executable for batch processes
-	var R = sv.tools.file.whereIs("R")
-	if (R == null & warn)
-	sv.alert("R is not found", "You should install or reinstall R" +
-		" on this machine (see http://cran.r-project.org). Under Windows" +
-		" you could also run RSetReg.exe from the /bin subdirectory of R" +
-		" install in case R is installed, but not recognized by SciViews).");
-	// Save the path in r.application prefs
-	if (R == null) R = "";
-	sv.pref.setPref("r.application", R, true);
-	return(R);
-}
-
-//// Print some text (command or results) in the local R console
-sv.r.print = function (text, newline, command, partial) {
-	// Default values for optional arguments
-	if (newline === undefined) newline = true;
-	if (command === undefined) command = false;
-	if (partial === undefined) partial = false;
-
-	// For now, use the command output pane
-	if (command) { // This is a R command
-		if (partial) {
-			sv.cmdout.message("R waits for more input...", 0, true);
-		} else { // This is a new command
-			sv.cmdout.clear();
-			sv.cmdout.message("R is calculating... " +
-			"(if it takes too long, switch to the R console:" +
-			" it could be waiting for some input)!", 0, true);
-			text = ":> " + text;
-		}
-	} else { // This is some data returned by R
-		if (!partial) sv.cmdout.message("R is ready!", 0, false);
-	}
-	sv.cmdout.append(text, newline);
-}
-
-// Tests:
-//sv.r.evalHidden("Sys.sleep(5); cat('done\n')");
-//sv.r.evalHidden("Sys.sleep(5); cat('done\n')", earlyExit = true);
-//sv.r.evalHidden("Sys.sleep(3); cat('done\n');" +
-//   " koCmd('alert(\"koCmd is back\");')", earlyExit = true);
-
 // Evaluate R expression and call procfun in Komodo with the result as argument
 // all additional arguments will be passed to procfun
 sv.r.evalCallback = function(cmd, procfun, context) {
@@ -152,7 +103,7 @@
 }
 
 sv.r.eval = function(cmd) sv.rconn.eval.call(sv.rconn, cmd)
-sv.r.evalHidden = function(cmd, earlyExit) sv.rconn.eval.call(sv.rconn, cmd)
+sv.r.evalHidden = function(cmd, earlyExit) sv.rconn.eval.call(sv.rconn, cmd, null, true)
 sv.r.escape = function (cmd) sv.rconn.escape(cmd);
 
 // Set the current working directory (to current buffer dir, or ask for it)
@@ -366,7 +317,6 @@
 //}
 
 
-
 // Get help in R (HTML format)
 sv.r.help = function (topic, pkg) {
 	var res = false;
@@ -727,11 +677,11 @@
 		// Save .RData & .Rhistory in the the session directory and clean WS
 		// We need also to restore .required variable (only if it exists)
 		cmd.push('if (exists(".required")) assignTemp(".required", .required)',
-				 'TempEnv()$.Last.sys()',
+				 'if(existsTemp(".Last.sys", "function")) do.call(".Last.sys", list(), envir = TempEnv())',
 				 'save.image(); savehistory()',
 				 'rm(list = ls())');
 	}
-	cmd.push('rm(list = ls())', '.required <- getTemp(".required")');
+	cmd.push('.required <- getTemp(".required")');
 
 	// Initialize the session
 	dir = sv.r.initSession(dir, datadir, scriptdir, reportdir);
@@ -746,7 +696,7 @@
 	// TODO: loadhistory APPENDS a history. Make R clear the current history first.
 	// Note: there seems to be no way to clear history without restarting R!
 	if (loadNew) {
-		cmd.push('if (file.exists(".RData")) load(".RData")',
+		cmd.push('sys.load.image(".RData", FALSE)',
 				 'if (file.exists(".Rhistory")) loadhistory()');
 
 		// Look for .Rprofile, in current, then in user directory (where else R looks for it?)
@@ -764,6 +714,8 @@
 		}
 	}
 
+	//sv.cmdout.append(cmd.join(";\n"));
+
 	// Execute the command in R (TODO: check for possible error here!)
 	// TODO: run first in R; make dirs in R; then change in Komodo!
 	sv.r.evalCallback(cmd.join(";\n"), function(data) {
@@ -935,7 +887,7 @@
 	//on Windows, "<HOME>/.R/repositories", "<R_installPath>/etc/repositories"
 }
 
-// Select CRAN mirror, with optional callback
+// Select CRAN mirror
 sv.r.pkg.chooseCRANMirror = function (setPref) {
 	var res = false;
 	var cmd = 'assignTemp("cranMirrors", getCRANmirrors(all = FALSE, local.only = FALSE));' +
@@ -975,7 +927,7 @@
 // List available packages on the selected repositories
 sv.r.pkg.available = function () {
 	var res = sv.r.eval('.pkgAvailable <- available.packages()\n' +
-	'as.character(.pkgAvailable[, "Package"])');
+		'as.character(.pkgAvailable[, "Package"])');
 	ko.statusBar.AddMessage(sv.translate(
 		"Looking for available R packages... please wait"),
 		"SciViews-K", 5000, true);

Modified: komodo/SciViews-K-dev/content/js/rconnection.js
===================================================================
--- komodo/SciViews-K-dev/content/js/rconnection.js	2011-08-08 20:47:13 UTC (rev 383)
+++ komodo/SciViews-K-dev/content/js/rconnection.js	2011-08-08 20:49:09 UTC (rev 384)
@@ -31,7 +31,6 @@
 
 sv.rconn = {};
 
-
 try { // DEBUG
 	sv.rconn.cleanUp();
 } catch(e) {}
@@ -58,6 +57,11 @@
 this.__defineGetter__ ('command', function () _svuSvc.lastCommand);
 this.__defineGetter__ ('result', function () _svuSvc.lastResult);
 
+
+// this ID is used to identify commands from the user
+this.userCommandId = _svuSvc.uid();
+
+
 // get list of running R processes
 this.listRProcesses = function(property) {
 	if (!property) property = "CommandLine";
@@ -67,6 +71,10 @@
 	return proc;
 }
 
+// TODO: IMPORTANT! background calls (e.g. object browser) need to have unique id.
+// but ID for user commands should be fixed (to allow for multiline)
+// sv.rconn.eval("1:100 ", null, false, "sv12345")
+
 // Evaluate in R //
 // arguments are handled in a non standard way:
 //sv.rconn.eval(command, callback, hidden, null, null, ...) - single use handler
@@ -81,51 +89,70 @@
 		args.splice(0, 2);
 		handlers[id].args = args;
 	} else {
-		if(!id) {
-			id = ((new Date()).getTime() + Math.random()).toString(16);
-			var sfx = 0; while ((id + sfx) in handlers) sfx++;
-			id += sfx;
-		} else {
+		if(!id)
+			// If no callback, it is an user command
+			id = callback? _svuSvc.uid() : this.userCommandId;
+		else
 			keep = true;
-		}
+
 		args.splice(0, 5);
 		handlers[id] = new _REvalListener(callback, keep, args, id);
 
 		if (prepareOnly) return id;
 	}
 	//if (mode == "e")	_this.printResults(result, command);
-	_svuSvc.execInRBgr(command, hidden? "h" : "e", id);
+	// TODO: 'id' should be one and the same for user commands,
+	// and unique for background calls
+
+	var mode = ['json']; if (hidden) mode.push('h');
+
+	_svuSvc.execInRBgr(command, mode.join(' '), id);
+	//_svuSvc.execInRBgr(command, hidden? "h" : "e", id);
 	return id;
 }
 
 // Evaluate in R quickly - and return result
 this.evalAtOnce = function(command, timeout) {
 	if(timeout == undefined) timeout = .5;
-	return _svuSvc.execInR(command, "h", timeout);
+	//return _svuSvc.execInR(command, "h", timeout).replace(/[\x02\x03]/g, '');
+	return _svuSvc.execInR(command, 'json h', timeout).replace(/[\x02\x03]/g, '');
 }
 
 this.escape = function(command) _svuSvc.escape(command);
 
+//this.testRAvailability = function(checkProc) {
+//	var result = _this.evalAtOnce("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);
+//	return connectionUp;
+//}
+
 this.testRAvailability = function(checkProc) {
-	var result = _this.evalAtOnce("cat(1)").trim();
-	var connectionUp = result == "1";
-	var rProcess = checkProc? _this.getRProc() : undefined;
-	var rProcessCount = (rProcess == undefined)? -1 : rProcess.length;
-	ret = '';
+	var result = _this.evalAtOnce("cat(123)");
+	var connectionUp = result.indexOf("123") != -1;
+	var 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.";
-		}
+		ret = "Cannot connect to R";
 	} else {
-		result = null;
-		ret += "Connection with R successful.";
+		ret = "Connection with R successful.";
 	}
-	//ko.dialogs.alert(ret, result, "R connection test");
 	sv.cmdout.append("R connection test:\n" + ret);
 	return connectionUp;
 }
@@ -133,6 +160,7 @@
 //_this.setObserver(rCallbackChunk, "r-command-chunk");
 //_this.setObserver(rCallback, "r-command-executed");
 
+// handles koCmd requests:
 var defaultRequestHandler = function(str) {
 	str = str.trim();
 	//sv.cmdout.append(str);
@@ -148,7 +176,7 @@
 	return "Received: [" + str + "]"; // echo
 }
 
-this.__defineGetter__ ('serverIsUp', function () _svuSvc.serverIsUp);
+this.__defineGetter__ ('serverIsUp', function () _svuSvc.serverIsUp() );
 
 this.startSocketServer = function(requestHandler) {
 	if(!requestHandler) requestHandler = defaultRequestHandler;
@@ -230,7 +258,7 @@
 			//[Exception... "Illegal operation on WrappedNative prototype
 			//object" nsresult: "0x8057000c (NS_ERROR_XPC_BAD_OP_ON_WN_PROTO)"]
 		}
-		if (mode == "e")	_this.printResults(result, command);
+		//if (mode == "e" || mode == "json")	_this.printResults(result, command, true);
 		return this.keep;
 	}
 }
@@ -240,26 +268,60 @@
 
 var _waitMessageTimeout;
 
-this.printResults = function(result, command, done) {
-	//var eol = ["\r\n", "\n", "\r"][document.getElementById
-		//("runoutput-scintilla").scimoz.eOLMode];
-	//doc.new_line_endings['\n', '\r', '\r\n']
+
+this.printCommandinfo = function(cinfo) {
+	cinfo.QueryInterface(Components.interfaces.svICommandInfo);
+	var result, prompt, styledResult;
+	switch (cinfo.message) {
+		case 'Not ready':
+			result = '...';
+			prompt = ':+';
+		break;
+		case 'Want more':
+		break;
+		case 'Parse error':
+		case 'Done':
+		default:
+			styledResult = cinfo.result? cinfo.styledResult() : '';
+	}
+
+	var scimoz = sv.cmdout.scimoz;
+	var readOnly = scimoz.readOnly;
+	scimoz.readOnly = false;
+	 // scimoz.gotoPos(sm.textLength); where?
+
+	// add command (style as code)
+
+	if (styledResult) scimoz.addStyledText(styledResult.length, styledResult);
+
+	// add final prompt (style as code)
+
+	scimoz.readOnly = readOnly;
+}
+
+
+
+this.printResults = function(result, command, executed, wantMore) {
+	//alert(result + "\n" + command +  "\n" + executed);
 	var msg;
 	command = _curCommand + _curPrompt + ' ' + command + sv.cmdout.eolChar;
 	window.clearTimeout(_waitMessageTimeout);
 
-	//if (result !== null) {
-	if (done) {
-		var newPrompt = _curPrompt;
-		var ff = result.lastIndexOf("\x0c"); // ("\f") = 3
-		if(ff != -1) {
-			newPrompt = result.substr(ff + 1, 2);
-			result = result.substr(0, ff) + newPrompt;
-		}
-		if (newPrompt == ':+')	_curCommand = command;
-			else	_curCommand = '';
+	if (executed) {
+		//var newPrompt = _curPrompt;
+		var newPrompt = wantMore? ':+' : ':>';
+		result = result + '\n' + newPrompt;
+		_curCommand = wantMore? command : '';
 		_curPrompt = newPrompt;
-		sv.cmdout.message(msg);
+
+		//var ff = result.lastIndexOf("\x0c"); // ("\f") = 3
+		//if(ff != -1) {
+		//	newPrompt = result.substr(ff + 1, 2);
+		//	result = result.substr(0, ff) + newPrompt;
+		//}
+		//_curCommand = (newPrompt == ':+')? command : '';
+		//_curPrompt = newPrompt;
+		sv.cmdout.message(null);
 	} else {
 		//alert(result == null)
 		result = '...';
@@ -267,22 +329,46 @@
 		// display 'wait message' only for longer operations
 		_waitMessageTimeout = window.setTimeout(sv.cmdout.message, 700, msg, 0, false);
 	}
-	sv.cmdout.print(command.replace(/^ {3}(?= *\S)/gm, ":+ ") + result);
+
[TRUNCATED]

To get the complete diff run:
    svnlook diff /svnroot/sciviews -r 384


More information about the Sciviews-commits mailing list