[Sciviews-commits] r275 - in komodo/SciViews-K/content: . js

noreply at r-forge.r-project.org noreply at r-forge.r-project.org
Tue May 11 21:53:26 CEST 2010


Author: prezez
Date: 2010-05-11 21:53:26 +0200 (Tue, 11 May 2010)
New Revision: 275

Modified:
   komodo/SciViews-K/content/default-keybindings.kkf
   komodo/SciViews-K/content/js/commands.js
   komodo/SciViews-K/content/js/r.js
   komodo/SciViews-K/content/js/robjects.js
   komodo/SciViews-K/content/js/socket.js
   komodo/SciViews-K/content/overlayMain.xul
Log:
Command controllers rewritten in somewhat more elegant way ('setKeybindings' and 'setControllers' are no longer public methods).
Tidied up command names.
sv.socket.serverIsStarted: more thorough checking whether Komodo's socket server is actually working.


Modified: komodo/SciViews-K/content/default-keybindings.kkf
===================================================================
--- komodo/SciViews-K/content/default-keybindings.kkf	2010-05-10 22:42:21 UTC (rev 274)
+++ komodo/SciViews-K/content/default-keybindings.kkf	2010-05-11 19:53:26 UTC (rev 275)
@@ -1,21 +1,21 @@
-version 17
+version 18
 
 # SciViews-K default keybindings
 # will be applied if no other key has been assigned by user, and if a key
-# combination is not used. Commands' ids must start with "cmd_sv_" and be
+# combination is not used. Commands' ids must start with "cmd_sv" and be
 # defined in the XUL overlay.
-# Copyright (c) 2009, Ph. Grosjean & K. Barton
+# Copyright (c) 2010, Ph. Grosjean & K. Barton
 # License: MPL 1.1/GPL 2.0/LGPL 2.1
 
-binding cmd_sv_RRunAll F5
-binding cmd_sv_RSourceAll Shift+F5
-binding cmd_sv_RRunLineOrSelection F6
-binding cmd_sv_RSourceLineOrSelection Shift+F6
-binding cmd_sv_RRunBlock F7
-binding cmd_sv_RSourceBlock Shift+F7
-binding cmd_sv_RRunLine F11
-binding cmd_sv_RRunPara F12
-binding cmd_sv_RSourcePara Shift+F12
-binding cmd_sv_RRunFunction Ctrl+F12
-binding cmd_sv_RSourceFunction Ctrl+Shift+F12
-binding cmd_sv_start_R Ctrl+F10
+binding cmd_svRRunAll F5
+binding cmd_svRSourceAll Shift+F5
+binding cmd_svRRunLineOrSelection F6
+binding cmd_svRSourceLineOrSelection Shift+F6
+binding cmd_svRRunBlock F7
+binding cmd_svRSourceBlock Shift+F7
+binding cmd_svRRunLine F11
+binding cmd_svRRunPara F12
+binding cmd_svRSourcePara Shift+F12
+binding cmd_svRRunFunction Ctrl+F12
+binding cmd_svRSourceFunction Ctrl+Shift+F12
+binding cmd_svStartR Ctrl+F10

Modified: komodo/SciViews-K/content/js/commands.js
===================================================================
--- komodo/SciViews-K/content/js/commands.js	2010-05-10 22:42:21 UTC (rev 274)
+++ komodo/SciViews-K/content/js/commands.js	2010-05-11 19:53:26 UTC (rev 275)
@@ -11,9 +11,8 @@
 // sv.command.setKeybindings(clearOnly); // Set SciViews-K default keybindings
 ///////////////////////////////////////////////////////////////////////////////
 
-if (typeof(sv.command) == 'undefined') {
-    sv.command = {};
-}
+if (typeof(sv) == 'undefined') sv = {};
+if (typeof(sv.command) == 'undefined') sv.command = {};
 
 // sv.command object constructor
 (function () {
@@ -102,7 +101,6 @@
 	"sciviewsk at sciviews.org", "defaults");
 	var cmd = sv.prefs.getString("svRApplication");
 
-
 	// PhG: there is a bug in the way R starts: at the begining, a dummy '00LOCK'
 	// file is created that prevents to config another R process as SciViews socket
 	// server. Everytime svStart.R is run, it looks if this '00LOCK' file exists,
@@ -145,11 +143,19 @@
 	//if (path) path += os.sep;
 	//TODO: shouldn't we replace this with a command line argument which would
 	// be more flexible, because it should allow much more than just --quiet???
+	// KB: work in progress...
+
+
 	var Quiet = sv.prefs.getString("svRQuiet")? "--quiet " : " ";
-
 	cmd = cmd.replace("%Path%", path).replace("%cwd%", cwd)
 		.replace("%title%", "SciViews-R").replace("%quiet%", Quiet);
 
+/*
+	var Args = sv.prefs.getString("svRArgs");
+	cmd = cmd.replace("%Path%", path).replace("%cwd%", cwd)
+		.replace("%title%", "SciViews-R").replace("%args%", Args);
+*/
+
 	var id = sv.prefs.getString("svRApplicationId");
 
 	// runIn = "command-output-window", "new-console",
@@ -190,22 +196,14 @@
 			break;
 		default:
 	}
-	//sv.cmdout.append("Running '" + cmd + "' in " + runIn + " / preferredRApp is" + preferredRApp);
-	//return;
 
 	ko.run.runCommand(window, cmd, cwd, env.join("\n"), false,
 		false, false, runIn, false, false, false);
 
-
-
-
-	//return cmd + "\n" + runIn;
-
 	// Register observer of application termination.
 	this.rObserver = new AppTerminateObserver(cmd);
 }
 
-
 	// This will observe status message notification to be informed about
 	// application being terminated. A more straightforward way would be to use
 	// runService.RunAndNotify but this wouldn't allow to start app in a console
@@ -238,7 +236,7 @@
 			sv.log.debug("R has been started with command: " + command);
 			// Sending commands to R does not seem to work, I think it is too early, R is still
 			// starting. This should be in .Rprofile
-			//sv.socket.updateCharset(true);
+			//sv.socket.updateRInfo(true);
 			// Possibly refresh the GUI by running SciViews-specific
 			// R task callbacks and make sure R Objects pane is updated
 			//sv.r.evalHidden("try(guiRefresh(force = TRUE), silent = TRUE)");
@@ -320,11 +318,9 @@
 		}
 
 		var rhelpTabbed = sv.prefs.getString("rhelp.tabbed", false) == "true";
-
 		var rHelpXulUri = "chrome://sciviewsk/content/RHelpWindow.xul";
 
 		// Open R-help in a right tab
-		// FIXME: opening in tab is still buggy
 		if (rhelpTabbed) {
 			// make sure tab is visible and select it:
 			var tabPanel = document.getElementById("rhelpviewbox");
@@ -376,78 +372,84 @@
 		//_this.RHelpWin.closed = true;
 	}
 
-	this.setControllers = function () {
-		//sv.log.debug("this.setControllers");
-		// Allow some commands only when R is running...
-		// using this needs solving an issue of running R in some terminals
-		// on linux (mac?) that send terminate signal right after start.
 
-		var vmProto = ko.views.viewManager.prototype;
+    function _setControllers () {
 
-		var cmdsIfRRunning = ['OpenPkgManager', 'BrowseWD', 'quit_R',
-			 'OpenHelp', 'sessionMgr']; //'update_charset',
-		var cmdsIfRNotRunning = ['start_R'];
+        //Based on: chrome://komodo/content/library/controller.js
+        // backwards compatibility APIs
+        xtk.include("controller");
+        var Controller = xtk.Controller;
 
-		// Make these commands active only when current document language is R
-		var cmdsIfIsRView = ["RunAll", "SourceAll", "RunBlock", "RunFunction",
-			"RunLine", "RunPara", "SourceBlock", "SourceFunction", "SourcePara",
-			"RunLineOrSelection", "SourceLineOrSelection"];
+        const XRRunning = 1, XRStopped = 2, XisRDoc = 4, XHasSelection = 8;
+        var handlers = {
+                'cmd_svOpenPkgManager': [ "sv.command.openPkgManager();", XRRunning ],
+                'cmd_svBrowseWD': [ 'sv.r.setwd(\'current\', true);', XRRunning ],
+                'cmd_svQuitR': [ 'sv.r.quit();', XRRunning ],
+                'cmd_svOpenHelp': [ "sv.command.openHelp();", XRRunning ],
+                'cmd_svSessionMgr': [ "sv.command.openSessionMgr();", XRRunning ],
+                'cmd_svStartR': [ 'sv.command.startR();', XRStopped ],
+                'cmd_svUpdateRInfo': [ 'sv.socket.updateRInfo(true);', XRRunning ],
+                'cmd_svRRunAll': [ 'sv.r.send("all");',XisRDoc | XRRunning ],
+                'cmd_svRSourceAll': [ 'sv.r.source("all");',XisRDoc | XRRunning ],
+                'cmd_svRRunBlock': [ 'sv.r.send("block");',XisRDoc | XRRunning ],
+                'cmd_svRRunFunction': [ 'sv.r.send("function");',XisRDoc | XRRunning ],
+                'cmd_svRRunLine': [ 'sv.r.send("line");',XisRDoc | XRRunning ],
+                'cmd_svRRunPara': [ 'sv.r.send("para");',XisRDoc | XRRunning ],
+                'cmd_svRSourceBlock': [ 'sv.r.source("block");',XisRDoc | XRRunning ],
+                'cmd_svRSourceFunction': [ 'sv.r.source("function");',XisRDoc | XRRunning ],
+                'cmd_svRSourcePara': [ 'sv.r.source("para");',XisRDoc | XRRunning ],
+                'cmd_svRRunLineOrSelection': [ 'sv.r.send("line/sel");',XisRDoc | XRRunning ],
+                'cmd_svRSourceLineOrSelection': [ 'sv.r.source("line/sel");',XisRDoc | XRRunning ],
+                'cmd_svRRunSelection': [ 'sv.r.send("sel");',XisRDoc | XRRunning | XHasSelection ],
+                'cmd_svRSourceSelection': [ 'sv.r.source("sel");', XisRDoc | XRRunning | XHasSelection ]
+        }
 
-		// ... and if some text is selected
-		var cmdsIfIsRViewAndSelection = ["RunSelection", "SourceSelection"];
+        //temporary:
+        function _isRRunning () {
+            return true;
+        }
+        function _isRCurLanguage () {
+            var view = ko.views.manager.currentView;
+            if (!view || !view.document)
+                return false;
+            return(view.document.language == 'R');
+        }
+        function _hasSelection () {
+            var view = ko.views.manager.currentView;
+            if (!view || !view.scimoz)
+                return false;
+            return ((view.scimoz.selectionEnd - view.scimoz.selectionStart) != 0);
+        }
 
-		function _setCommandCtrl1 (arr, fun, pfx) {
-			pfx = "is_cmd_" + pfx;
-			for (var i in arr) {
-				vmProto[pfx + arr[i] + "_supported"] = fun;
-				vmProto[pfx + arr[i] + "_enabled"] = fun;
-			}
-		}
+        function svController() {}
+        svController.prototype = new Controller();
+        svController.prototype.constructor = svController;
+        svController.prototype.destructor = function() { }
 
-// PhG: currently, all menu items remain enabled, because this feature
-//      does not work well, and menus are sometimes disabled when they shouldn't be!
+        svController.prototype.isCommandEnabled = function(command) {
+            if(!command in handlers) return false;
 
-// KB: temporarily _isRRunning always == true so items are disabled only if current language is not R
+            var test = handlers[command][1];
+            return (((test & XRRunning) != XRRunning) || _isRRunning())
+            && (((test & XRStopped) != XRStopped) || !_isRRunning())
+            && (((test & XisRDoc) != XisRDoc) || _isRCurLanguage())
+            && (((test & XHasSelection) != XHasSelection) || _hasSelection());
+        }
 
-		//_setCommandCtrl1(cmdsIfRRunning, _isRRunning, "sv_");
-		//_setCommandCtrl1(cmdsIfRNotRunning, function() {
-		//	return !_isRRunning()}, "sv_");
-		_setCommandCtrl1(cmdsIfIsRView, _RControl_supported, "sv_R");
-		_setCommandCtrl1(cmdsIfIsRViewAndSelection,
-			_RControlSelection_supported, "sv_R");
+        svController.prototype.supportsCommand = svController.prototype.isCommandEnabled;
 
-		vmProto.do_cmd_sv_quit_R = function () sv.r.quit();
+        svController.prototype.doCommand = function(command) {
+            if (command in handlers) {
+                return eval(handlers[command][0]);
+            };
+            return false;
+        }
 
-		vmProto.do_cmd_sv_update_charset = function () {
-			sv.socket.updateCharset(true);
-			window.setTimeout(function() {
-				sv.log.info(sv.translate("R uses \"%S\" encoding.",
-				sv.socket.charset));
-			}, 100);
-		};
+        window.controllers.appendController(new svController());
 
-		//TODO: check if R is working before any command is sent,
-		//rather than continously
-		//_keepCheckingR();
+        //sv.log.debug("Controllers has been set.");
+}
 
-
-		vmProto.do_cmd_sv_RRunLine = function() sv.r.send("line");
-		vmProto.do_cmd_sv_RRunAll = function()	sv.r.send("all");
-		vmProto.do_cmd_sv_RSourceAll = function() sv.r.source("all");
-		vmProto.do_cmd_sv_RSourcePara = function()	sv.r.source("para");
-		vmProto.do_cmd_sv_RRunPara = function() sv.r.send("para");
-		vmProto.do_cmd_sv_RRunSelection = function() sv.r.send("sel");
-		vmProto.do_cmd_sv_RSourceSelection = function() sv.r.source("sel");
-		vmProto.do_cmd_sv_RRunLineOrSelection = function() sv.r.send("line/sel");
-		vmProto.do_cmd_sv_RSourceLineOrSelection =
-			function() sv.r.source("line/sel");
-		vmProto.do_cmd_sv_RRunBlock = function() sv.r.send("block");
-		vmProto.do_cmd_sv_RSourceBlock = function() sv.r.source("block");
-		vmProto.do_cmd_sv_RRunFunction = function() sv.r.send("function");
-		vmProto.do_cmd_sv_RSourceFunction = function() sv.r.source("function");
-		vmProto.do_cmd_sv_start_R = function() sv.command.startR();
-	}
-
 // Code below is for extra items in editor context menu (eg. "run selection"),
 // Commented out because it is still buggy
 //	function editorContextMenuOnShowing (event) {
@@ -473,11 +475,12 @@
 	// Set default keybindings from file
 	// chrome://sciviewsk/content/default-keybindings.kkf
 	// preserving user modified ones and avoiding key conflicts
-	this.setKeybindings = function (clearOnly) {
+	function _setKeybindings (clearOnly) {
 		var keybindingSvc = Components
 			.classes["@activestate.com/koKeybindingSchemeService;1"]
 			.getService(Components.interfaces.koIKeybindingSchemeService);
 
+//TODO: use of gKeybindingMgr could simplify this code
 		//gKeybindingMgr.keybindingSchemeService
 
 		var svSchemeDefault = sv.tools.file
@@ -489,7 +492,7 @@
 		var sch = keybindingSvc.getScheme(currentSchemeName);
 
 		//gKeybindingMgr.parseConfiguration
-		var bindingRx = /[\r\n]+(# *SciViews|binding cmd_sv_.*)/g;
+		var bindingRx = /[\r\n]+(# *SciViews|binding cmd_sv.*)/g;
 		if (clearOnly != true) {
 			function _getSvKeys (data, pattern) {
 				if (!pattern) pattern = "";
@@ -503,7 +506,7 @@
 				return res;
 			}
 
-			var svCmdPattern = "cmd_sv_";
+			var svCmdPattern = "cmd_sv";
 			var svKeysDefault = _getSvKeys (svSchemeDefault, svCmdPattern);
 			var svKeysCurrent = _getSvKeys (sch.data, svCmdPattern);
 
@@ -539,7 +542,7 @@
 				"SciViews keybindings have been updated in \"" +
 				currentSchemeName + "\" scheme.");
 		} else {
-			//gKeybindingMgr.removeCommandsWithPrefix("cmd_sv_");
+			//gKeybindingMgr.removeCommandsWithPrefix("cmd_sv");
 			sch.data = sch.data.replace(bindingRx, "");
 			sv.log.debug("SciViews keybindings have been cleared in \"" +
 				currentSchemeName + "\" scheme.");
@@ -552,14 +555,16 @@
 
 		// A (temporary) hack to allow for R autocompletion/calltips to be
 		// triggered with the same key-shortcut as for other languages.
-		// cmd_sv_RTriggerCompletion will exit for files other than R
+		// cmd_svRTriggerCompletion will exit for files other than R
 		//var tpc_cmd = document.getElementById("cmd_triggerPrecedingCompletion");
 		//tpc_cmd.setAttribute("oncommand", [tpc_cmd.getAttribute("oncommand"),
-		//	"ko.commands.doCommandAsync('cmd_sv_RTriggerCompletion',
+		//	"ko.commands.doCommandAsync('cmd_svRTriggerCompletion',
 		//  event);"].join(";"));
+        //sv.log.debug("Keybindings has been applied.");
+
 	}
-}).apply(sv.command);
 
+    addEventListener("load", _setControllers, false);
+    addEventListener("load", _setKeybindings, false);
 
-addEventListener("load", sv.command.setControllers, false);
-addEventListener("load", sv.command.setKeybindings, false);
+}).apply(sv.command);

Modified: komodo/SciViews-K/content/js/r.js
===================================================================
--- komodo/SciViews-K/content/js/r.js	2010-05-10 22:42:21 UTC (rev 274)
+++ komodo/SciViews-K/content/js/r.js	2010-05-11 19:53:26 UTC (rev 275)
@@ -136,7 +136,7 @@
 				// Remove message in the statusbar
 				sv.cmdout.message("");
 				// update character set used by R
-				sv.socket.updateCharset(true);
+				sv.socket.updateRInfo(true);
 				window.setTimeout(function() {
 					sv.log.info(sv.translate("R uses \"%S\" encoding.",
 					sv.socket.charset));

Modified: komodo/SciViews-K/content/js/robjects.js
===================================================================
--- komodo/SciViews-K/content/js/robjects.js	2010-05-10 22:42:21 UTC (rev 274)
+++ komodo/SciViews-K/content/js/robjects.js	2010-05-11 19:53:26 UTC (rev 275)
@@ -178,6 +178,7 @@
 		var cmd = 'print(objList(id = "' + id + '_' + pack + '", envir = "' +
 			pack + '", all.info = FALSE, compare = FALSE), sep = "' + sep +
 			'", eol = "\\n", raw.output = TRUE, header = TRUE)';
+		//TODO: Use cmdPattern instead
 
 		sv.log.debug(cmd);
 		sv.r.evalCallback(cmd, _parseObjectList, pack);
@@ -289,6 +290,7 @@
 		_createVisibleData();
 	};
 
+//TODO: merge with _addObjectList
 	function _addSubObject (obj) {
 		var objName = obj.origItem.name;
 		// objList does not quote non syntactic names, so we do it here
@@ -305,10 +307,11 @@
 			'", envir = "' + env + '", object = "' + objName +
 			'", all.info = FALSE, compare = FALSE), sep = "' + sep +
 			'", eol = "\\n")';
-		sv.log.debug(cmd);
+		//TODO: Use cmdPattern instead
 		sv.r.evalCallback(cmd, _parseSubObjectList, obj);
 	};
 
+//TODO: merge with _parseObjectList
 	function _parseSubObjectList (data, obj) {
 		var lines = data.split(/[\r\n]{1,2}/);
 
@@ -319,6 +322,8 @@
 			return;
 		}
 
+
+
 		// This is only for compatibility with different print.objList versions
 		// may be removed when final form of output will be estabilished
 		// get rid of the "Objects list:" line
@@ -358,6 +363,7 @@
 		origItem.children = [];
 		for (var i = 2; i < lines.length; i++) {
 			if (lines[i].indexOf(sep) != -1) {
+
 				line = lines[i].split(sep);
 				if (line.length < 6)
 					continue;
@@ -654,7 +660,6 @@
 		var vd = this.visibleData;
 		var item = vd[idx];
 		if (!item) {
-			//sv.log.debug(idx);
 			return;
 		}
 
@@ -663,7 +668,6 @@
 			_addSubObject(item);
 			return;
 		}
-
 		var rowsChanged;
 		var iLevel = item.level;
 

Modified: komodo/SciViews-K/content/js/socket.js
===================================================================
--- komodo/SciViews-K/content/js/socket.js	2010-05-10 22:42:21 UTC (rev 274)
+++ komodo/SciViews-K/content/js/socket.js	2010-05-11 19:53:26 UTC (rev 275)
@@ -23,27 +23,24 @@
 //
 // sv.socket.serverStart();     // Start the SciViews-K socket server
 // sv.socket.serverStop();      // Stop the SciViews-K socket server
-// sv.socket.serverIsStarted(); // Is the socket server currently started?
+// sv.socket.serverIsStarted;   // (read-only property) Is the socket server currently started?
 // sv.socket.serverConfig();    // Get a short description of server config
 // sv.socket.serverWrite(data); // Write a string through the socket server
 // sv.socket.updateCharset(force); // Update R character set
 ////////////////////////////////////////////////////////////////////////////////
 //
 // TODO: use svSocketMinVersion to check svSocket R package is not too old!
-// TODO: start the socket server automatically when Komodo is launched
 
-
 // Define the 'sv.socket' namespace
 if (typeof(sv.socket) == 'undefined')
 	sv.socket = {};
 
 (function () {
 
+	var _this = this;
 	/////// Socket client //////////////////////////////////////////////////////
 	this.svSocketMinVersion = "0.9-48";	// Will be used later for compatibility
 										// checking between R and Komodo tools
-	//this.host = "127.0.0.1";	// Host to connect to (local host only, currently)
-	//host address is now controlled by the preference value "sciviews.server.host"
 	this.cmdout = true;			// Do we write to 'Command Output'?
 	this.prompt = ":> ";		// The prompt, could be changed to continue prompt
 	this.cmd = "";				// The command to send to R
@@ -210,131 +207,130 @@
 
 
 	/////// Socket server //////////////////////////////////////////////////////
-	this.debug = sv.log.isAll();	// Set to true for debugging mode
+	//this.debug = sv.log.isAll();	// Set to true for debugging mode
 	this.serverIsLocal = true;		// Is the socket servicing only localhost?
 
 	const nsITransport = Components.interfaces.nsITransport;
 
 	var _serverSocket;				// The SciViews-K socket server object
-	var _serverStarted = false;		// Is the socket server started?
 	var _inputString;				// The string with command send by R
 	var _outputString;				// The string with the result to send to R
 	var _output = [];
 	//debug only:
 	this.serverSocket = _serverSocket;
 
-	// Core function for the SciViews-K socket server:
-	// create the _serverSocket object
-	this.serverStart = function () {
-		if (this.debug) sv.log.debug("Socket server: serverStart");
+	// The following two methods implement nsIServerSocketListener:
+	this.onSocketAccepted = function (socket, transport) {
+		try {
+			if (_this.debug)
+				sv.log.debug("Socket server: onSocketAccepted!");
 
-		if (_serverStarted) try {
-			_serverSocket.close();
-			_serverStarted = false;
-		} catch(e) {
-			sv.log.exception(e, "sv.socket.serverStart() failed to close the" +
-				" socket before reopening it");
-		}
+			// Make sure to clean input and output strings before use
+			_inputString = "";
+			_outputString = "";
+			_output = [];
+			if (_this.debug)
+				sv.log.debug("Socket server: " + transport.host +
+					" on port " + transport.port + "\n");
 
-		var listener = {
-			onSocketAccepted : function (socket, transport) {
-				try {
-					if (this.debug)
-						sv.log.debug("Socket server: onSocketAccepted!");
+			// Then, read data from the client
+			var inputStream = transport.openInputStream(nsITransport.
+				OPEN_BLOCKING, 0, 0);
+			var sin = Components.
+				classes["@mozilla.org/scriptableinputstream;1"]
+				.createInstance(Components.interfaces.
+				nsIScriptableInputStream);
+			sin.init(inputStream);
 
-					// Make sure to clean input and output strings before use
-					_inputString = "";
-					_outputString = "";
-					_output = [];
-					if (this.debug)
-						sv.log.debug("Socket server: " + transport.host +
-							" on port " + transport.port + "\n");
+			var date = new Date();
+			do {
+				_inputString = sin.read(512);
+			} while(_inputString == "" && ((new Date()) - date < millis))
 
-					// Then, read data from the client
-					var inputStream = transport.openInputStream(nsITransport.
-						OPEN_BLOCKING, 0, 0);
-					var sin = Components.
-						classes["@mozilla.org/scriptableinputstream;1"]
-						.createInstance(Components.interfaces.
-						nsIScriptableInputStream);
-					sin.init(inputStream);
+			// Read the complete data
+			while (sin.available() > 0)
+				_inputString += sin.read(512);
 
-					var date = new Date();
-					do {
-						_inputString = sin.read(512);
-					} while(_inputString == "" && ((new Date()) - date < millis))
+			if (converter.charset) try {
+				_inputString = converter.ConvertToUnicode(_inputString);
+			} catch (e) {
+				sv.log.exception(e, "Socket server: onSocketAccepted()" +
+					" is unable to convert to Unicode");
+			}
 
-					// Read the complete data
-					while (sin.available() > 0)
-						_inputString += sin.read(512);
+			// Is there data send?
+			if (_inputString == "") {
+				//_outputString += "Error: no command send!\n"
+				_output.push("Error: no command send!");
+			} else {
+				// Process the command
+				if (this.debug)
+					sv.log.debug("Command send by the client:\n" +
+						_inputString);
+				try {
+					eval(_inputString);
+				} catch(e) {
+					_output.push(e.toString());
+				}
+			}
+			if (_this.debug) sv.log.debug(_output.length?
+				("Result:\n" + _output.join("\n")) :
+				("Nothing to return to the socket client")
+			);
 
-					if (converter.charset) try {
-						_inputString = converter.ConvertToUnicode(_inputString);
-					} catch (e) {
-						sv.log.exception(e, "Socket server: onSocketAccepted()" +
-							" is unable to convert to Unicode");
-					}
+			// And finally, return the result to the socket client
+			// (append \n at the end)
+			_outputString = _output.join("\n") + "\n";
 
-					// Is there data send?
-					if (_inputString == "") {
-						//_outputString += "Error: no command send!\n"
-						_output.push("Error: no command send!");
-					} else {
-						// Process the command
-						if (this.debug)
-							sv.log.debug("Command send by the client:\n" +
-								_inputString);
-						try {
-							eval(_inputString);
-						} catch(e) {
-							_output.push(e.toString());
-						}
-					}
-					if (this.debug) sv.log.debug(_output.length?
-						("Result:\n" + _output.join("\n")) :
-						("Nothing to return to the socket client")
-					);
+			if (converter.charset) try {
+				_outputString = converter.ConvertFromUnicode(_outputString);
+			} catch(e) {
+				sv.log.exception(e, "Socket server: onSocketAccepted()" +
+					" is unable to convert from Unicode");
+			}
 
-					// And finally, return the result to the socket client
-					// (append \n at the end)
-					_outputString = _output.join("\n") + "\n";
+			var outputStream = transport.openOutputStream(nsITransport.
+				OPEN_BLOCKING, 0, 0);
+			outputStream.write(_outputString, _outputString.length);
+		} catch(e) {
+			sv.log.exception(e, "Socket server: onSocketAccepted()," +
+				" unmanaged error");
+		} finally {
+			// Make sure that streams are closed
+			outputStream.close();
+			inputStream.close();
+			if (_this.debug) sv.log.debug("SocketAccepted: end");
+		}
+	};
 
-					if (converter.charset) try {
-						_outputString = converter.
-							ConvertFromUnicode(_outputString);
-					} catch(e) {
-						sv.log.exception(e, "Socket server: onSocketAccepted()" +
-							" is unable to convert from Unicode");
-					}
+	this.onStopListening = function (socket, status) {
+		// The connection is closed by the client
+		if (_this.debug) sv.log.debug("(onStopListening) Socket server closed");
+	};
+	// End of 'nsIServerSocketListener' methods.
 
-					var outputStream = transport.openOutputStream(nsITransport.
-						OPEN_BLOCKING, 0, 0);
-					outputStream.write(_outputString, _outputString.length);
-				} catch(e) {
-					sv.log.exception(e, "Socket server: onSocketAccepted()," +
-						" unmanaged error");
-				} finally {
-					// Make sure that streams are closed
-					outputStream.close();
-					inputStream.close();
-					if (this.debug) sv.log.debug("SocketAccepted: end");
-				}
-			},
 
-			onStopListening : function (socket, status) {
-				// The connection is closed by the client
-				if (this.debug) sv.log.debug("Socket server closed");
-			}
-		};
+	// Core function for the SciViews-K socket server:
+	// create the _serverSocket object
+	this.serverStart = function () {
+		if (this.debug) sv.log.debug("Socket server: serverStart");
 
+		if (this.serverIsStarted) try {
+			_serverSocket.close();
+		} catch(e) {
+			sv.log.exception(e, "sv.socket.serverStart() failed to close the" +
+				" socket before reopening it");
+		}
+
 		try {
 			_serverSocket = Components.
 				classes["@mozilla.org/network/server-socket;1"]
 				.createInstance(Components.interfaces.nsIServerSocket);
 			var port = sv.prefs.getString("sciviews.server.socket", "7052");
 			_serverSocket.init(port, this.serverIsLocal, -1);
-			_serverSocket.asyncListen(listener);
-			_serverStarted = true;
+			_serverSocket.asyncListen(_this);
+
+			this.serverSocket = _serverSocket;
 		} catch(e) {
 			sv.log.exception(e, "SciViews-K cannot open a server socket on port " +
 				port + ".\nMake sure the port is not already used by another" +
@@ -345,13 +341,13 @@
 			// chrome://sciviewsk/content/js/socket.js :: anonymous :: line 285
 		}
 		if (this.debug)
-			sv.log.debug("Socket server started");
+			sv.log.debug("serverStart: Socket server started");
 		sv.cmdout.message("SciViews-K socket server started", 2000, true);
 	}
 
 	// Stop the SciViews-K socket server
 	this.serverStop = function () {
-		if (_serverStarted) {
+		if (this.serverIsStarted) {
 			try {
 				_serverSocket.close();
 			} catch(e) {
@@ -359,7 +355,6 @@
 					" close the socket", true);
 			}
 
-			_serverStarted = false;
 			if (this.debug) sv.log.debug("Socket server stopped");
 			sv.cmdout.message("SciViews-K socket server stopped", 2000, true);
 		} else {
@@ -368,14 +363,26 @@
 	}
 
 	// Is the SciViews-K socket server started?
-	this.serverIsStarted = function () {
-		return(_serverStarted);
-	}
+	this.__defineGetter__ ('serverIsStarted', function () {
+		// Use brute force to find out whether socketServer is initiated and listening
+		if(typeof sv.socket.serverSocket == "undefined")
+			return false;
 
+		try {
+			this.serverSocket.asyncListen(this);
+		} catch(e) {
+			if (e.name == "NS_ERROR_IN_PROGRESS")		return true;
+			else if (e.name == "NS_ERROR_NOT_INITIALIZED")	return false;
+			else
+				sv.log.exception(e);
+		}
+		return true;
+	});
+
 	// What is the current SciViews-K socket server config?
 	this.serverConfig = function () {
 		var serverStatus = " (stopped)"
-		if (_serverStarted) serverStatus = " (started)"
+		if (this.serverIsStarted) serverStatus = " (started)"
 		var port = sv.prefs.getString("sciviews.server.socket", "7052");
 		if (this.serverIsLocal) {
 			return("Local socket server on port " + port + serverStatus);
@@ -386,7 +393,7 @@
 
 	// Write to the socket server, use this to return something to the client
 	this.serverWrite = function (data) {
-		if (_serverStarted) {
+		if (this.serverIsStarted) {
 			_output.push(data);
 		} else {
 			sv.alert("The socket server in unavailable",
@@ -395,19 +402,18 @@
 		}
 	}
 
-	this.__defineGetter__ ('charset', function () {
-		return converter.charset;
-	});
-	this.__defineSetter__ ('charset', function (x) {
+	this.__defineGetter__ ('charset', function () converter.charset);
+	this.__defineSetter__ ('charset', function (charset) {
 		try {
-			converter.charset = x;
+			converter.charset = charset;
 		} catch (e) {
 			_charsetUpdated = false;
 		}
 		return converter.charset;
 	});
 
-	this.updateCharset = function (force) {
+	// Changed name to updateCharset
+	this.updateRInfo = function (force) {
 		if (!force && _charsetUpdated) return;
 		//if (this.debug) sv.log.debug("charsetUpdate");
 		_charsetUpdated = true;
@@ -429,10 +435,12 @@
 
 	// [PhG] The following command raises an error on my Mac
 	//window.setTimeout(this.serverStart, 500);
-	//window.setTimeout(this.updateCharset, 100);
+	//window.setTimeout(this.updateRInfo, 100);
 	//this.charset = 'cp1250';
 }).apply(sv.socket);
 
 // [PhG] This raises an error on Komodo 5.1 on Mac OS X
 //addEventListener("load", sv.socket.serverStart, false);
-window.setTimeout(sv.socket.serverStart, 500);
+
+//KB: Does this work on Mac?
+addEventListener("load", function() window.setTimeout(sv.socket.serverStart, 500), false);

Modified: komodo/SciViews-K/content/overlayMain.xul
===================================================================
--- komodo/SciViews-K/content/overlayMain.xul	2010-05-10 22:42:21 UTC (rev 274)
+++ komodo/SciViews-K/content/overlayMain.xul	2010-05-11 19:53:26 UTC (rev 275)
@@ -81,23 +81,23 @@
 		<commandset id="cmdset_rApp" commandupdater="true"
 			oncommandupdate="ko.commands.updateCommandset(this);"
 			events="r_app_started_closed">
-			<command id="cmd_sv_start_R" key="key_cmd_sv_start_R"
-				oncommand="ko.commands.doCommand('cmd_sv_start_R');"
+			<command id="cmd_svStartR" key="key_cmd_svStartR"
+				oncommand="ko.commands.doCommand('cmd_svStartR');"
 				desc="R: &StartR;" label="&StartR;" accesskey="&StartR.key;"/>
-			<command id="cmd_sv_quit_R" key="key_cmd_sv_quit_R"
-				oncommand="ko.commands.doCommand('cmd_sv_quit_R');"
+			<command id="cmd_svQuitR" key="key_cmd_svQuitR"
+				oncommand="ko.commands.doCommand('cmd_svQuitR');"
 				desc="R: &QuitR;" label="&QuitR;" accesskey="&QuitR.key;"/>
-			<command id="cmd_sv_OpenPkgManager" key="key_cmd_sv_OpenPkgManager"
-				oncommand="sv.command.openPkgManager();" disabled="false"
+			<command id="cmd_svOpenPkgManager" key="key_cmd_svOpenPkgManager"
+				oncommand="ko.commands.doCommand('cmd_svOpenPkgManager');" disabled="false"
 				desc="R: &pkgMgr;" label="&pkgMgr;" accesskey="&pkgMgr.key;"/>
-			<command id="cmd_sv_OpenHelp" key="key_cmd_sv_OpenHelp"
-				oncommand="sv.command.openHelp();"
+			<command id="cmd_svOpenHelp" key="key_cmd_svOpenHelp"
+				oncommand="ko.commands.doCommand('cmd_svOpenHelp');"
 				desc="R: &helpStart;" label="&helpStart;" accesskey="&helpStart.key;"/>
-			<command id="cmd_sv_BrowseWD" key="key_cmd_sv_BrowseWD"
-				oncommand="sv.r.setwd('current', true);"
+			<command id="cmd_svBrowseWD" key="key_cmd_svBrowseWD"
+				oncommand="ko.commands.doCommand('cmd_svBrowseWD');"
 				desc="R: &svBrowseWD;" label="&svBrowseWD;" accesskey="&svBrowseWD.key;"/>
-			<command id="cmd_sv_sessionMgr" key="key_cmd_sv_sessionMgr"
-				oncommand="sv.command.openSessionMgr();"
+			<command id="cmd_svSessionMgr" key="key_cmd_svSessionMgr"
+				oncommand="ko.commands.doCommand('cmd_svSessionMgr');"
 				desc="R: &svOpenSessMgr;" label="&svOpenSessMgr;" accesskey="&svOpenSessMgr.key;"/>
 		</commandset>
 
@@ -107,49 +107,49 @@
 		<commandset id="cmdset_r_control" commandupdater="true"
 		  events="current_view_language_changed,language_changed,current_view_changed,r_app_started_closed"
 		  oncommandupdate="ko.commands.updateCommandset(this);">
-			<command id="cmd_sv_RRunAll" key="key_cmd_sv_RRunAll"
-				oncommand="ko.commands.doCommand('cmd_sv_RRunAll')"
+			<command id="cmd_svRRunAll" key="key_cmd_svRRunAll"
+				oncommand="ko.commands.doCommand('cmd_svRRunAll')"
 				desc="R: &rSendFile;" label="&rSendFile;" accesskey="&rSendFile.key;"/>
-			<command id="cmd_sv_RSourceAll" key="key_cmd_sv_RSourceAll"
-				oncommand="ko.commands.doCommand('cmd_sv_RSourceAll')"
+			<command id="cmd_svRSourceAll" key="key_cmd_svRSourceAll"
+				oncommand="ko.commands.doCommand('cmd_svRSourceAll')"
 				desc="R: &rSrcFile;" label="&rSrcFile;" accesskey="&rSrcFile.key;"/>
-			<command id="cmd_sv_RRunBlock" key="key_cmd_sv_RRunBlock"
-				oncommand="ko.commands.doCommand('cmd_sv_RRunBlock')"
+			<command id="cmd_svRRunBlock" key="key_cmd_svRRunBlock"
+				oncommand="ko.commands.doCommand('cmd_svRRunBlock')"
 				desc="R: &rSendBlock;" label="&rSendBlock;" accesskey="&rSendBlock.key;"/>
-			<command id="cmd_sv_RRunFunction" key="key_cmd_sv_RRunFunction"
-				oncommand="ko.commands.doCommand('cmd_sv_RRunFunction')"
+			<command id="cmd_svRRunFunction" key="key_cmd_svRRunFunction"
+				oncommand="ko.commands.doCommand('cmd_svRRunFunction')"
 				desc="R: &rSendFun;" label="&rSendFun;" accesskey="&rSendFun.key;"/>
-			<command id="cmd_sv_RRunLine" key="key_cmd_sv_RRunLine"
-				oncommand="ko.commands.doCommand('cmd_sv_RRunLine')"
+			<command id="cmd_svRRunLine" key="key_cmd_svRRunLine"
[TRUNCATED]

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


More information about the Sciviews-commits mailing list