5 // Created by Byron Ellis on 6/25/07.
6 // Copyright 2007 __MyCompanyName__. All rights reserved.
9 #import "RInterpreter.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>
34 @interface RInterpreter (Private)
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;
43 @implementation RInterpreter
45 + (RInterpreter*)sharedInterpreter {
46 static RInterpreter *interp = nil;
47 if(nil == interp) interp = [[RInterpreter alloc] init];
52 if(nil == [super init]) return nil;
54 //Some configuration defaults
56 buffer = [[NSMutableAttributedString alloc] init];
65 deviceList = [[NSMutableArray alloc] init];
66 evalLock = [[NSLock alloc] init];
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);
83 - (BOOL)isConfigured { return configured; }
85 - (void)setArgv:(char**)argv argc:(int)argc {
90 - (id)delegate { return delegate; }
91 - (void)setDelegate:(id)aDelegate { delegate = aDelegate; }
93 - (long)bufferSize { return bufferSize; }
94 - (void)setBufferSize:(long)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);
115 if(nil != delegate) [delegate didBeginEvaluationForInterpreter:self];
117 [self registerInterface];
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 %@");
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]) {
146 NSLog(@"Unable to register server. Presently, a maximum of 16 local execution servers are allowed per machine");
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) {
156 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
165 - (void)awakeConsole {
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)
176 data2:0] atStart:NO];
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) {
196 NSMutableData *data = [[NSMutableData alloc] init];
197 [data serialize:obj];
199 return [data autorelease];
204 - (BOOL)deserializeObject:(NSData*)anObject withName:(NSString*)aName replace:(BOOL)shouldReplace error:(NSError**)error {
206 if(anObject == nil) {
207 *error = [NSError errorWithDomain:@"org.r-project.RExecServer" code:1 userInfo:nil];
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];
218 Rf_setVar(install(name),[anObject unserialize],R_GlobalEnv);
222 - (void)copyObjectWithName:(NSString*)aName toServer:(NSString*)aServer error:(NSError**)error {
223 id theProxy = [[NSConnection rootProxyForConnectionWithRegisteredName:aServer host:nil] retain];
225 NSData *serialized = [self serializeObjectWithName:aName error:error];
227 [theProxy deserializeObject:serialized withName:aName replace:YES error:error];
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();
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,
270 extern void Rstd_WriteConsole(char*,int);
272 @implementation RInterpreter (Private)
277 char *argv_orig[] = {"R","--gui=cocoa","--no-save","--no-restore-data"};
282 int i,j,has_gui=0,has_g=0;
285 for(i=1;i<_argc;i++) {
286 if(strncmp(_argv[i],"-g",2)==0)
288 else if(strncmp(_argv[i],"--gui",5)==0)
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);
297 for(i=0;i<_argc;i++) {
298 if(strncmp(_argv[i],"-g",2)==0) {
300 } else if(strncmp(_argv[i],"--gui",5)==0) {
302 argv[j++] = _argv[i];
305 argv[j++] = "--gui=cocoa";
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];
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.
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;
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];
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;
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];
364 while((dev = (RDevice*)[e nextObject]) != nil) {
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];
373 if(nil != delegate) [delegate didGetInputForInterpreter:self];
375 if(nil != delegate) [delegate didBeginEvaluationForInterpreter:self];
377 return readerBufferUsed;
380 - (void)removeDevice:(NSNotification*)aNotify {
381 if(nil != delegate) [delegate didCloseDevice:[aNotify object] forInterpreter:self];
382 [deviceList removeObject:[aNotify object]];
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];
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 {
426 - (void)system:(char*)cmd {
430 - (int)editFile:(char*)aFileName {
431 if(YES == allowTerminal) {
432 NSLog(@"Editing file: %s",aFileName);
439 - (int)showFiles:(int)nfiles file:(char**)file headers:(char**)headers wtitle:(char*)wtitle del:(Rboolean)del pager:(char*)pager {
443 - (int)customPrintType:(char*)aType list:(SEXP)aList {
444 NSLog(@"This is hosed for right now. Might need support from R itself.");
448 - (SEXP)selectListWithCall:(SEXP)call op:(SEXP)op args:(SEXP)args rho:(SEXP)rho {
452 - (void)readyToEvaluate {
453 [NSApp postEvent:[NSEvent otherEventWithType:NSApplicationDefined
454 location:NSMakePoint(0,0)
461 data2:0] atStart:NO];
464 SEXP RES_ServerName() {
465 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
466 const char *str = [[[RInterpreter sharedInterpreter] serverName] UTF8String];
468 PROTECT(ret = allocVector(STRSXP,1));
469 SET_STRING_ELT(ret,0,mkChar(str));
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];
485 Rf_error("Problem copying object");
489 static const R_CallMethodDef R_CallDef[] = {
490 {"RES_ServerName",(DL_FUNC)RES_ServerName,0},
491 {"RES_CopyObject",(DL_FUNC)RES_CopyObject,2},
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);
506 #ifdef R_USING_TRAMPOLINE
508 void RInterp_Suicide(char*aMsg) {
509 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
510 [[RInterpreter sharedInterpreter] suicide:aMsg];
513 void RInterp_ShowMessage(char*aMsg) {
514 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
515 [[RInterpreter sharedInterpreter] showMessage:aMsg];
518 void RInterp_FlushConsole() {
519 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
520 [[RInterpreter sharedInterpreter] flushConsole];
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];
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];
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)
554 data2:0] atStart:NO];
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];
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];