Refactoring terminal routines into TerminalDelegate
[RExecServer.git] / RInterpreter.m
blob251824a635b1a787c673bb28281492ba13996014
1 //
2 //  RInterpreter.m
3 //  RExecServer
4 //
5 //  Created by Byron Ellis on 6/25/07.
6 //  Copyright 2007 __MyCompanyName__. All rights reserved.
7 //
9 #import "RInterpreter.h"
10 #import "RDevice.h"
11 #import "DeviceWindowController.h"
12 #import "NSData+RSerialize.h"
13 #import "TerminalDelegate.h"
15 #define R_INTERFACE_PTRS 1
16 #define CSTACK_DEFNS     1
18 #include <Rinternals.h>
19 #include <Rinterface.h>
20 #include <R_ext/Utils.h>
21 #include <Rgraphics.h>
22 #include <R_ext/GraphicsDevice.h>
23 #include <R_ext/eventloop.h>
24 #include <R_ext/Rdynload.h>
25 #include <Rversion.h>
27 #include <pthread.h>
28 #include <signal.h>
31 #undef Boolean
32 #undef error
34 @interface RInterpreter (Private)
35 - (void)configure;
36 - (void)readyToEvaluate;
37 - (Rboolean)openDevice:(NewDevDesc *)dev withDisplay:(char *)display width:(double)width height:(double)height
38         pointsize:(double)ps family:(char*)family antialias:(Rboolean)antialias autorefresh:(Rboolean)autorefreash 
39         quartzpos:(int)quartzpos background:(int)bg;
40 - (void)registerInterface;
41 @end
43 @implementation RInterpreter
45 + (RInterpreter*)sharedInterpreter {
46         static RInterpreter *interp = nil;
47         if(nil == interp) interp = [[RInterpreter alloc] init];
48         return interp;
51 - (id)init {
52         if(nil == [super init]) return nil;
53         
54         //Some configuration defaults
55         bufferSize           = 2048;
56         buffer               = [[NSMutableAttributedString alloc] init];
59         suppressOutput       = NO;
60         allowTerminal        = NO;
61         vend                 = YES;
62         waiting              = YES;
63         delegate             = nil;
65         deviceList = [[NSMutableArray alloc] init];
66         evalLock   = [[NSLock alloc] init];
67         
68         _argc = 0;
69         _argv = NULL;
71         outputTag = [[NSDictionary alloc] initWithObjectsAndKeys:@"ROutput",@"RTextType",nil];
72         promptTag = [[NSDictionary alloc] initWithObjectsAndKeys:@"RInput",@"RTextType",nil];
73         errorTag  = [[NSDictionary alloc] initWithObjectsAndKeys:@"RError",@"RTextType",nil];
75         //Set some environment variables to their defaults if they are not presently set.
76         setenv("R_HOME",[[[NSBundle bundleWithIdentifier:@"org.r-project.R-framework"] resourcePath] UTF8String],0);
77         setenv("LANG",[[NSString stringWithFormat:@"%@.UTF-8",[[NSLocale currentLocale] localeIdentifier]] UTF8String],0);
78         return self;
83 - (BOOL)isConfigured { return configured; }
85 - (void)setArgv:(char**)argv argc:(int)argc {
86         _argc = argc;
87         _argv = argv;
90 - (id)delegate { return delegate; }
91 - (void)setDelegate:(id)aDelegate { delegate = aDelegate; }
93 - (long)bufferSize   { return bufferSize; }
94 - (void)setBufferSize:(long)aSize {
95         bufferSize = aSize;
97 - (BOOL)allowTerminal { return allowTerminal; }
98 - (void)setAllowTerminal:(BOOL)aBool { allowTerminal = aBool; }
100 - (BOOL)vend { return vend; }
101 - (void)setVend:(BOOL)aBool { vend = aBool; }
103 - (NSString*)homePath { return (NULL == getenv("R_HOME")) ? nil : [NSString stringWithUTF8String:getenv("R_HOME")]; }
104 - (void)setHomePath:(NSString*)aPath {
105         setenv("R_HOME",[aPath UTF8String],1);
108 - (NSString*)localeIdentifier { return (NULL == getenv("LANG")) ? nil : [NSString stringWithUTF8String:getenv("LANG")]; }
109 - (void)setLocaleIdentifier:(NSString*)aLocale {
110         setenv("LANG",[aLocale UTF8String],1);
113 - (void)_run {
114         [evalLock lock];
115         if(nil != delegate) [delegate didBeginEvaluationForInterpreter:self];
116         setup_Rmainloop();
117         [self registerInterface];
118         run_Rmainloop();
121 - (void)run {
122         if(NO == [self isConfigured]) [self configure];
123         if(YES == [self vend]) {
124                 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
125                 if(NULL != getenv("RVENDNAME")) {
126                         vendName = [[NSString alloc] initWithUTF8String:getenv("RVENDNAME")];
127                         NSConnection *conn = [NSConnection defaultConnection];
128                         [conn setRootObject:self];
129                         if(NO == [conn registerName:vendName]) {
130                                 NSLog(@"Unable to register server as %@");
131                                 [vendName release];
132                                 vendName = nil;
133                         }
134                 } else {
135                         int vend_num = 0;
136                         NSConnection *conn = [NSConnection defaultConnection];
137                         [conn setRootObject:self];
138                         while(vend_num < 17) {
139                                 vendName = [[NSString alloc] initWithFormat:@"R Execution Server %d",++vend_num];
140                                 if(YES == [conn registerName:vendName]) {
141                                         break;
142                                 } else
143                                         [vendName release];
144                         }
145                         if(vend_num == 11) {
146                                 NSLog(@"Unable to register server. Presently, a maximum of 16 local execution servers are allowed per machine");
147                                 vendName = nil;
148                         }
149                 }
150                 [pool release];
151         }
152         //If we don't have a delegate yet, enter the event loop. The delegate (when it connects)
153         //should post a stop message via awakeConsole.
154         if(nil == delegate) {
155                 waiting = YES;
156                 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
157                 [NSApp run];
158                 [pool release];
159         }
160         waiting = NO;
161         [self _run];
165 - (void)awakeConsole {
166         if(YES == waiting) {
167                 //Post a stop event so that we fall out of the wait loop at the 
168                 [NSApp postEvent:[NSEvent otherEventWithType:NSApplicationDefined 
169                                                                                 location:NSMakePoint(0,0)
170                                                                                 modifierFlags:0
171                                                                                 timestamp:0 
172                                                                                 windowNumber:0 
173                                                                                 context:nil 
174                                                                                 subtype:1337 
175                                                                                 data1:0 
176                                                                                 data2:0] atStart:NO];   
177         }
180 - (void)evaluateInput:(NSString*)aString {
181         readerBufferUsed = [aString length];
182         if(readerBufferUsed > readerBufferLength) readerBufferUsed = readerBufferLength;
183         memcpy(readerBuffer,[aString UTF8String],sizeof(unsigned char)*readerBufferUsed);
184         [self readyToEvaluate];
187 - (NSArray*)devices { return deviceList; }
189 - (NSString*)serverName { return vendName; }
191 - (NSData*)serializeObjectWithName:(NSString*)anName error:(NSError**)anError {
192         const char *name = [anName UTF8String];
193         SEXP  obj  = findVar(install(name),R_GlobalEnv);
194         if(obj != R_UnboundValue) {
195                 PROTECT(obj);
196                 NSMutableData *data = [[NSMutableData alloc] init];
197                 [data serialize:obj];
198                 UNPROTECT(1);
199                 return [data autorelease];
200         } else { 
201                 return nil;
202         }
204 - (BOOL)deserializeObject:(NSData*)anObject withName:(NSString*)aName replace:(BOOL)shouldReplace error:(NSError**)error {
205         error = nil;
206         if(anObject == nil) {
207                 *error = [NSError errorWithDomain:@"org.r-project.RExecServer" code:1 userInfo:nil];
208                 return NO;
209         }
210         
211         
212         const char *name = [aName UTF8String];
213         SEXP  cur  = findVar(install(name),R_GlobalEnv);
214         if(cur != R_UnboundValue && NO == shouldReplace) {
215                 *error = [NSError errorWithDomain:@"org.r-project.RExecServer" code:1 userInfo:nil];
216                 return NO;
217         }
218         Rf_setVar(install(name),[anObject unserialize],R_GlobalEnv);
219         return YES;
222 - (void)copyObjectWithName:(NSString*)aName toServer:(NSString*)aServer error:(NSError**)error {
223         id theProxy = [[NSConnection rootProxyForConnectionWithRegisteredName:aServer host:nil] retain];
224         *error = nil;
225         NSData *serialized = [self serializeObjectWithName:aName error:error];
226         if(nil == error) 
227                 [theProxy deserializeObject:serialized withName:aName replace:YES error:error];
228         [theProxy release];
231 @end
234 #pragma mark Function Prototypes
235 void RInterp_Suicide(char*);
236 void RInterp_ShowMessage(char*);
237 void RInterp_FlushConsole();
238 void RInterp_WritePrompt(char*);
239 int  RInterp_ReadConsole(char*,unsigned char*,int,int);
240 void RInterp_ResetConsole();
241 void RInterp_WriteConsole(char*,int);
242 void RInterp_ClearerrConsole();
243 void RInterp_Busy();
244 void RInterp_CleanUp(SA_TYPE,int,int);
245 int  RInterp_ShowFiles(int,char**,char**,char*,Rboolean,char*);
246 int  RInterp_ChooseFile(int,char*,int);
247 int  RInterp_EditFile(char*);
248 void RInterp_System(char*);
249 void RInterp_ProcessEvents();
250 Rboolean RInterp_Device(NewDevDesc*,char*,double,double,double,char*,Rboolean,Rboolean,int,int);
251 void RInterp_DeviceParams(double*,double*,double*,char*,Rboolean*,Rboolean*,int*);
252 int  RInterp_CustomPrint(char *,SEXP);
253 SEXP RInterp_do_selectlist(SEXP,SEXP,SEXP,SEXP);
257 extern void     (*ptr_R_ProcessEvents)(void);
258 extern void     (*ptr_CocoaSystem)(char*);
259 extern Rboolean (*ptr_CocoaInnerQuartzDevice)(NewDevDesc*,char*,double,double,double,char*,Rboolean,Rboolean,int,int);
260 extern void     (*ptr_CocoaGetQuartzParameters)(double*,double*,double*,char*,Rboolean*,Rboolean*,int*);
261 extern int      (*ptr_Raqua_CustomPrint)(char *, SEXP);
263 extern DL_FUNC ptr_do_wsbrowser,
264     ptr_do_dataentry, ptr_do_browsepkgs, ptr_do_datamanger,
265     ptr_do_packagemanger, ptr_do_flushconsole, ptr_do_hsbrowser,
266     ptr_do_selectlist;
267         
270 extern void Rstd_WriteConsole(char*,int);
272 @implementation RInterpreter (Private)
274 - (void)_dummy { }
276 - (void)configure {
277         char *argv_orig[] = {"R","--gui=cocoa","--no-save","--no-restore-data"};
278         char **argv;
279         int   argc = 0;
280         
281         if(_argc > 0) {
282                 int i,j,has_gui=0,has_g=0;
283                 
284                 argc=_argc;
285                 for(i=1;i<_argc;i++) {
286                         if(strncmp(_argv[i],"-g",2)==0) 
287                                 has_g = 1; 
288                         else if(strncmp(_argv[i],"--gui",5)==0)
289                                 has_gui = 1;
290                 }
291                 if(has_g || has_gui)
292                         printf("warning: Execution server will ignore GUI settings.\n");
293                 if(has_g) argc -= 1; else if(!has_g && !has_gui) argc++;
294                 argv = malloc(sizeof(char*)*argc);
295                 
296                 j=0;
297                 for(i=0;i<_argc;i++) {
298                         if(strncmp(_argv[i],"-g",2)==0) {
299                                 i++;
300                         } else if(strncmp(_argv[i],"--gui",5)==0) {
301                         } else {
302                                 argv[j++] = _argv[i];
303                         }
304                 }
305                 argv[j++] = "--gui=cocoa";
306         } else {
307                 argc = 4;
308                 argv = argv_orig;
309         }
310         Rf_initialize_R(argc,argv);
311         //R_GUIType = "RExecServer";    //We are NOT the Aqua GUI, but not being the aqua gui is even more annoying.
312         if(YES == allowTerminal) {
313                 TerminalDelegate *tempDel = [[TerminalDelegate alloc] init];
314                 [tempDel setReaderFunction:ptr_R_ReadConsole];
315                 [tempDel setWriterFunction:Rstd_WriteConsole];
316                 [tempDel setFlushFunction:ptr_R_FlushConsole];
317                 [self setDelegate:tempDel];
318         }
319         R_Outputfile  = NULL;
320         R_Consolefile = NULL;
322 #ifdef R_USING_TRAMPOLINE
323 //On systems supporting libffi we can generate a direct trampoline
324 //function that dispatches to the R level. This is coming later.
325 #else
326     ptr_R_Suicide                = RInterp_Suicide;
327     ptr_R_ShowMessage            = RInterp_ShowMessage;
328     ptr_R_ReadConsole            = RInterp_ReadConsole;
329     ptr_R_WriteConsole           = RInterp_WriteConsole;
330         ptr_R_WriteConsoleEx         = NULL;
331     ptr_R_ShowFiles              = RInterp_ShowFiles;
332     ptr_R_EditFile               = RInterp_EditFile;
333     ptr_R_ChooseFile             = RInterp_ChooseFile;
334     ptr_Raqua_CustomPrint        = RInterp_CustomPrint;
335         ptr_R_ProcessEvents          = RInterp_ProcessEvents;
336     ptr_CocoaInnerQuartzDevice   = RInterp_Device;
337     ptr_CocoaGetQuartzParameters = RInterp_DeviceParams;
338     ptr_CocoaSystem              = RInterp_System;
339 #endif
340         
341         //Put ourselves into a multithreaded state
342         //[NSThread detachNewThreadSelector:@selector(_dummy) toTarget:self withObject:nil];
345 - (void)writeConsole:(char*)output length:(int)aLength {
346         char c = output[aLength];
347         output[aLength] = '\0';
348         if(nil != delegate) [delegate appendString:[NSString stringWithUTF8String:output] ofType:0 forInterpreter:self];
349         output[aLength] = c;
352 - (int)readConsoleWithPrompt:(char*)aPrompt buffer:(unsigned char*)aBuffer length:(int)aLength history:(int)useHistory {
353         //Put those there for something that wants to write a string
354         readerPrompt = aPrompt;
355         readerBuffer = aBuffer;
356         readerBufferLength = aLength;
357         readerAddToHistory = useHistory;
358         
359         //Flush any drawing that may have happened since the last time we were here.
360         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
361         if(nil != delegate) [delegate didFinishEvaluationForInterpreter:self];
362         NSEnumerator *e = [deviceList objectEnumerator];
363         RDevice *dev;
364         while((dev = (RDevice*)[e nextObject]) != nil) {
365                 [dev flushDrawing];
366         }
367         [pool release];
368         [evalLock unlock];
369         pool = [[NSAutoreleasePool alloc] init];
370         if(nil != delegate) [delegate appendString:[NSString stringWithUTF8String:aPrompt] ofType:2 forInterpreter:self];
371         if(nil != delegate) [delegate didBeginWaitingForInputWithMaximumLength:readerBufferLength addToHistory:(useHistory == 1) ? YES : NO forInterpreter:self];
372         [NSApp run];
373         if(nil != delegate) [delegate didGetInputForInterpreter:self];
374         [evalLock lock];
375         if(nil != delegate) [delegate didBeginEvaluationForInterpreter:self];
376         [pool release];
377         return readerBufferUsed;
380 - (void)removeDevice:(NSNotification*)aNotify {
381         if(nil != delegate) [delegate didCloseDevice:[aNotify object] forInterpreter:self];
382         [deviceList removeObject:[aNotify object]];
384         
385 - (Rboolean)openDevice:(NewDevDesc *)dev withDisplay:(char *)display width:(double)width height:(double)height
386         pointsize:(double)ps family:(char*)family antialias:(Rboolean)antialias autorefresh:(Rboolean)autorefreash 
387         quartzpos:(int)quartzpos background:(int)bg {
388         NSString *aDisplay = [NSString stringWithUTF8String:display];
389         NSArray  *bits     = [[aDisplay componentsSeparatedByString:@":"] retain];
390         Class deviceClass = nil;
391         deviceClass = [RDevice deviceForDisplay:([bits count] < 2) ? @"" : [bits objectAtIndex:1]];
393         //Can't create device.
394         if(nil == deviceClass) return 0;
395         RDevice *rd = [[deviceClass alloc] initWithDevice:dev size:NSMakeSize(width,height) pointSize:ps 
396                 display:[bits objectAtIndex:0]
397                 target:[bits count] < 2 ? nil : [bits objectAtIndex:1] background:bg antialias:antialias];
398         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeDevice:) name:@"RDeviceClosed" object:rd];
399         [deviceList addObject:rd];
400         if(nil != delegate) [delegate didOpenDevice:rd forInterpreter:self];
401         [rd finishOpening];
402         [rd release];
403         return TRUE;
406 - (void)flushConsole {
409 - (void)showMessage:(char*)aMsg {
410         [self writeConsole:aMsg length:strlen(aMsg)];
413 - (void)suicide:(char*)aMsg {
414         [self writeConsole:aMsg length:strlen(aMsg)];
417 - (void)resetConsole {
420 - (void)clearErrorConsole {
423 - (void)busy {
426 - (void)system:(char*)cmd {
427         system(cmd);
430 - (int)editFile:(char*)aFileName {
431         if(YES == allowTerminal) {
432                 NSLog(@"Editing file: %s",aFileName);
433                 return 0;
434         } else {
435                 return 0;
436         }
439 - (int)showFiles:(int)nfiles file:(char**)file headers:(char**)headers wtitle:(char*)wtitle del:(Rboolean)del pager:(char*)pager {
440         return 0;
443 - (int)customPrintType:(char*)aType list:(SEXP)aList {
444         NSLog(@"This is hosed for right now. Might need support from R itself.");
445         return 0;
448 - (SEXP)selectListWithCall:(SEXP)call op:(SEXP)op args:(SEXP)args rho:(SEXP)rho {
449         return R_NilValue;
452 - (void)readyToEvaluate {
453         [NSApp postEvent:[NSEvent otherEventWithType:NSApplicationDefined 
454                                                                         location:NSMakePoint(0,0)
455                                                                          modifierFlags:0
456                                                                          timestamp:0 
457                                                                          windowNumber:0 
458                                                                          context:nil 
459                                                                          subtype:1337 
460                                                                          data1:0 
461                                                                          data2:0] atStart:NO];  
464 SEXP RES_ServerName() {
465         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
466         const char *str = [[[RInterpreter sharedInterpreter] serverName] UTF8String];
467         SEXP ret;
468         PROTECT(ret = allocVector(STRSXP,1));
469         SET_STRING_ELT(ret,0,mkChar(str));
470         UNPROTECT(1);
471         [pool release];
472         return ret;
475 SEXP RES_CopyObject(SEXP name,SEXP server) {
476         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
477         NSString *aStr = [[NSString alloc] initWithUTF8String:CHAR(STRING_ELT(name,0))];
478         NSString *bStr = [[NSString alloc] initWithUTF8String:CHAR(STRING_ELT(server,0))];
479         NSError *error = nil;
480         [[RInterpreter sharedInterpreter] copyObjectWithName:aStr toServer:bStr error:&error];
481         [aStr release];
482         [bStr release];
483         [pool release];
484         if(nil != error)
485                 Rf_error("Problem copying object");
486         return R_NilValue;
489 static const R_CallMethodDef R_CallDef[] = {
490         {"RES_ServerName",(DL_FUNC)RES_ServerName,0},
491         {"RES_CopyObject",(DL_FUNC)RES_CopyObject,2},
492         NULL
495 extern void
496 R_addCallRoutine(DllInfo *info, const R_CallMethodDef * const croutine,void*sym);
498 - (void)registerInterface {
499 #if R_VERSION >= R_Version(2,6,0) 
500         R_registerRoutines(R_getEmbeddingDllInfo(),NULL,R_CallDef,NULL,NULL);
501 #endif
504 @end
506 #ifdef R_USING_TRAMPOLINE
507 #else
508 void RInterp_Suicide(char*aMsg) { 
509         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
510         [[RInterpreter sharedInterpreter] suicide:aMsg]; 
511         [pool release];
513 void RInterp_ShowMessage(char*aMsg) { 
514         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
515         [[RInterpreter sharedInterpreter] showMessage:aMsg]; 
516         [pool release];
518 void RInterp_FlushConsole() { 
519         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
520         [[RInterpreter sharedInterpreter] flushConsole]; 
521         [pool release];
523 int  RInterp_ReadConsole(char*prompt,unsigned char*buffer,int length,int history) {
524         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
525         int ret = [[RInterpreter sharedInterpreter] readConsoleWithPrompt:prompt buffer:buffer length:length history:history];
526         [pool release];
527         return ret;
529 void RInterp_ResetConsole() { [[RInterpreter sharedInterpreter] resetConsole]; }
530 void RInterp_WriteConsole(char*buffer,int length) { 
531         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
532         [[RInterpreter sharedInterpreter] writeConsole:buffer length:length]; 
533         [pool release];
535 void RInterp_ClearerrConsole() { [[RInterpreter sharedInterpreter] clearErrorConsole]; }
536 void RInterp_Busy() { [[RInterpreter sharedInterpreter] busy]; }
537 void RInterp_CleanUp(SA_TYPE type,int a,int b) { }
538 int  RInterp_ShowFiles(int a,char**b,char**c,char*d,Rboolean e,char*f) { 
539         return [[RInterpreter sharedInterpreter] showFiles:a file:b headers:c wtitle:d del:e pager:f];
541 int  RInterp_ChooseFile(int a,char*b,int c) { return 0; }
542 int  RInterp_EditFile(char*a) { return [[RInterpreter sharedInterpreter] editFile:a]; }
543 void RInterp_System(char*a) { [[RInterpreter sharedInterpreter] system:a]; }
544 void RInterp_ProcessEvents() { 
545         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
546         [NSApp postEvent:[NSEvent otherEventWithType:NSApplicationDefined 
547                                                                         location:NSMakePoint(0,0)
548                                                                          modifierFlags:0
549                                                                          timestamp:0 
550                                                                          windowNumber:0 
551                                                                          context:nil 
552                                                                          subtype:1337 
553                                                                          data1:0 
554                                                                          data2:0] atStart:NO];
555         [NSApp run];
556         [pool release];
558 Rboolean RInterp_Device(NewDevDesc *dev,
559         char *display,double width,double height,
560         double ps,char *family,Rboolean antialias,Rboolean autorefresh,int quartzpos,int bg) {
561         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
562         Rboolean ret = [[RInterpreter sharedInterpreter] openDevice:dev
563          withDisplay:display width:width height:height pointsize:ps family:family
564           antialias:antialias autorefresh:autorefresh quartzpos:quartzpos background:bg];
565         [pool release];
566         return ret;
568 void RInterp_DeviceParams(double*a,double*b,double*c,char*d,Rboolean*e,Rboolean*f,int*g) { }
569 int  RInterp_CustomPrint(char *a,SEXP b) { return [[RInterpreter sharedInterpreter] customPrintType:a list:b]; }
571 SEXP RInterp_do_selectlist(SEXP call,SEXP op,SEXP args,SEXP rho) {
572         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
573         SEXP ret = [[RInterpreter sharedInterpreter] selectListWithCall:call op:op args:args rho:rho];
574         [pool release];
575         return ret;
578 #endif