forked from R-macos/Mac-GUI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RController.m
4066 lines (3464 loc) · 139 KB
/
RController.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* R.app : a Cocoa front end to: "R A Computer Language for Statistical Data Analysis"
*
* R.app Copyright notes:
* Copyright (C) 2004-14 The R Foundation
* written by Stefano M. Iacus and Simon Urbanek
*
*
* R Copyright notes:
* Copyright (C) 1995-1996 Robert Gentleman and Ross Ihaka
* Copyright (C) 1998-2001 The R Development Core Team
* Copyright (C) 2002-2004 The R Foundation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* A copy of the GNU General Public License is available via WWW at
* http://www.gnu.org/copyleft/gpl.html. You can also obtain it by
* writing to the Free Software Foundation, Inc., 59 Temple Place,
* Suite 330, Boston, MA 02111-1307 USA.
*
* $Id: RController.m 8095 2022-06-24 10:46:39Z urbaneks $
*/
#import "RGUI.h"
#include <R.h>
#include <Rinternals.h>
#include <R_ext/Parse.h>
//#include <Fileio.h>
#include <Rinterface.h>
#include <langinfo.h>
#include <locale.h>
#include <R_ext/QuartzDevice.h>
#import <sys/fcntl.h>
#import <sys/select.h>
#import <sys/types.h>
#import <sys/time.h>
#import <sys/wait.h>
#import <signal.h>
#import <unistd.h>
#import "RController.h"
#import "REngine/Rcallbacks.h"
#import "REngine/REngine.h"
#import "RDocumentWinCtrl.h"
#import "Tools/Authorization.h"
#import "RChooseEncodingPopupAccessory.h"
#import "NSTextView_RAdditions.h"
#import "RWindow.h"
#import "Preferences.h"
#import "SearchTable.h"
// R defines "error" which is deadly as we use open ... with ... error: where error then gets replaced by Rf_error
#ifdef error
#undef error
#endif
// size of the console output cache buffer
#define DEFAULT_WRITE_BUFFER_SIZE 32768
// high water-mark of the buffer - it's [length - x] where x is the smallest possible size to be flushed before a new string will be split.
#define writeBufferHighWaterMark (DEFAULT_WRITE_BUFFER_SIZE-4096)
// low water-mark of the buffer - if less than the water mark is available then the buffer will be flushed
#define writeBufferLowWaterMark 2048
#define kR_WebViewSearchWindowHeight 27
/* RController.m: main GUI code originally based on Simon Urbanek's work of embedding R in Cocoa app (RGui?)
The Code and File Completion is due to Simon U.
History handler is due to Simon U.
*/
typedef struct {
ParseStatus status;
int prompt_type;
int browselevel;
unsigned char buf[1025];
unsigned char *bufp;
} R_ReplState;
extern R_ReplState state;
void run_Rmainloop(void); // from Rinit.c
extern void RGUI_ReplConsole(SEXP rho, int savestack, int browselevel); // from Rinit.c
extern int RGUI_ReplIteration(SEXP rho, int savestack, int browselevel, R_ReplState *state);
// from Defn.h
int R_SetOptionWidth(int);
#import "RController.h"
#import "Tools/CodeCompletion.h"
#import "Tools/FileCompletion.h"
#import "HelpManager.h"
#import "RDocument.h"
#import "PackageManager.h"
#import "DataManager.h"
#import "PackageInstaller.h"
#import "WSBrowser.h"
#import "HelpManager.h"
#import "RDocumentController.h"
#import "SelectList.h"
#import "VignettesController.h"
#import <unistd.h>
#import <sys/fcntl.h>
static RController* sharedRController;
static inline const char* NSStringUTF8String(NSString* self)
{
typedef const char* (*SPUTF8StringMethodPtr)(NSString*, SEL);
static SPUTF8StringMethodPtr SPNSStringGetUTF8String;
if (!SPNSStringGetUTF8String) SPNSStringGetUTF8String = (SPUTF8StringMethodPtr)[NSString instanceMethodForSelector:@selector(UTF8String)];
const char* to_return = SPNSStringGetUTF8String(self, @selector(UTF8String));
return to_return;
}
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_7
// declare the following methods to avoid compiler warnings
@interface NSWindow (SuppressWarnings)
- (void)toggleFullScreen:(id)sender;
@end
#endif
@interface R_WebViewSearchWindow : NSWindow
@end
@interface NSDocumentControllerWithAutosave : NSDocumentController
- (void)_autoreopenDocuments;
@end
@implementation R_WebViewSearchWindow
- (BOOL)canBecomeKeyWindow { return YES; }
- (BOOL)acceptsMouseMovedEvents { return YES; }
@end
@interface NSApplication (ScriptingSupport)
- (id)handleDCMDCommand:(NSScriptCommand*)command;
@end
@implementation NSApplication (ScriptingSupport)
- (id)handleDCMDCommand:(NSScriptCommand*)command
{
// if (![[[RController sharedController] getRConsoleWindow] isKeyWindow]) {
// [[[RController sharedController] getRConsoleWindow] makeKeyWindow];
// SLog(@" RConsole set to key window");
// }
NSDictionary *args = [command evaluatedArguments];
NSString *cmd = [args objectForKey:@""];
if (!cmd || [cmd isEqualToString:@""])
return [NSNumber numberWithBool:NO];
[[RController sharedController] sendInput: cmd];
/* post an event to wake the event loop in order to process the command */
int wn = [[[RController sharedController] getRConsoleWindow] windowNumber];
// SLog(@"Key window number %d", wn);
[NSApp postEvent:[NSEvent otherEventWithType: NSApplicationDefined
location: (NSPoint){0,0} modifierFlags: 0 timestamp: 0
windowNumber: wn context: NULL subtype: 0 data1: 0 data2: 0
] atStart: YES];
return [NSNumber numberWithBool:YES];
}
@end
@implementation RController
- (id) init {
self = [super init];
runSystemAsRoot = NO;
toolbar = nil;
toolbarStopItem = nil;
rootFD = -1;
childPID = 0;
RLtimer = nil;
lastShownWD = nil;
busyRFlag = YES;
appLaunched = NO;
terminating = NO;
processingEvents = NO;
breakPending = NO;
isREditMode = NO;
ignoreMagnifyingEvent = NO;
outputPosition = promptPosition = committedLength = lastCommittedLength = 0;
consoleInputQueue = [[NSMutableArray alloc] initWithCapacity:8];
currentConsoleInput = nil;
forceStdFlush = NO;
writeBufferLen = DEFAULT_WRITE_BUFFER_SIZE;
writeBufferPos = writeBuffer = (char*) malloc(writeBufferLen);
writeBufferType = 0;
readConsTransBufferSize = 1024; // initial size - will grow as needed
readConsTransBuffer = (char*) malloc(readConsTransBufferSize);
textViewSync = [[NSString alloc] initWithString:@"consoleTextViewSemahphore"];
searchInWebViewWindow = nil;
consoleColorsKeys = [[NSArray alloc] initWithObjects:
backgColorKey, inputColorKey, outputColorKey, promptColorKey,
stderrColorKey, stdoutColorKey, rootColorKey, selectionColorKey, nil];
defaultConsoleColors = [[NSArray alloc] initWithObjects: // default colors
[NSColor whiteColor], [NSColor blueColor], [NSColor blackColor], [NSColor purpleColor],
[NSColor redColor], [NSColor grayColor], [NSColor purpleColor], [NSColor colorWithCalibratedRed:0.71f green:0.835f blue:1.0f alpha:1.0f], nil];
consoleColors = [defaultConsoleColors mutableCopy];
filteredHistory = nil;
specialCharacters = [[NSCharacterSet characterSetWithCharactersInString:@"\r\b\a"] retain];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(windowWillCloseNotifications:)
name:NSWindowWillCloseNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(helpSearchTypeChanged)
name:@"HelpSearchTypeChanged"
object:nil];
lastFunctionForHint = [[NSString stringWithString:@""] retain];
lastFunctionHintText = nil;
appSupportPath = nil;
return self;
}
- (void) setRootFlag: (BOOL) flag
{
if (!flag) removeRootAuthorization();
runSystemAsRoot=flag;
{
NSArray * ia = [toolbar items];
int l = [ia count], i=0;
while (i<l) {
NSToolbarItem *ti = [ia objectAtIndex:i];
if ([[ti itemIdentifier] isEqual:AuthenticationToolbarItemIdentifier]) {
[ti setImage: [NSImage imageNamed: flag?@"lock-unlocked":@"lock-locked"]];
break;
}
i++;
}
}
}
- (BOOL) getRootFlag { return runSystemAsRoot; }
- (void) setRootFD: (int) fd {
rootFD=fd;
}
- (NSFont*) currentFont
{
return ([consoleTextView font]) ? [consoleTextView font] : [Preferences unarchivedObjectForKey:RConsoleDefaultFont withDefault:[NSFont fontWithName:@"Monaco" size:11]];
}
/**
* AppleScript handler for kAEOpenDocuments
* before NSApplication is ready, we need to catch any odoc events that arrive, otherwise we loose them
*/
- (void)handleAppleEventAEOpenDocuments:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent
{
SLog(@"RController.handleAppleEvent is called");
NSAppleEventDescriptor *openEvents = [event paramDescriptorForKeyword:keyDirectObject];
if(!openEvents) {
NSLog(@" - no open events found");
return;
}
int docs = [openEvents numberOfItems];
int i = 0;
SLog(@" - %d files to open", docs);
while (i <= docs) {
NSAppleEventDescriptor *d = [openEvents descriptorAtIndex:i];
if (d) {
CFURLRef url;
d = [d coerceToDescriptorType:typeFSRef];
url = CFURLCreateFromFSRef(kCFAllocatorDefault, [[d data] bytes]);
if (url) {
NSString *pathName = (NSString *)CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);
[pathName autorelease];
if (!appLaunched) {
[pendingDocsToOpen addObject:pathName];
SLog(@" appending %@ to open after launching", pathName);
} else {
SLog(@" openFile %@", pathName);
[self application:NSApp openFile:pathName];
}
CFRelease(url);
}
}
i++;
}
}
- (NSTouchBar *)makeTouchBar
{
// Create TouchBar object
SLog(@"makeTouchBar");
NSTouchBar *touchBar = [[NSTouchBar alloc] init];
touchBar.delegate = self;
touchBar.customizationIdentifier = @"org.R-project.R.app.console";
// Set the default ordering of items.
touchBar.defaultItemIdentifiers = @[@"foo", NSTouchBarItemIdentifierOtherItemsProxy];
touchBar.customizationAllowedItemIdentifiers = @[@"foo"];
touchBar.principalItemIdentifier = @"foo";
return touchBar;
}
/* This is user's library path as interpreted by the R GUI. Note that
during initialization the GUI has no access to R_LIBS_USER, because
the Rprofile has not been loaded yet.
Also note that the GUI preference to add the user path pre-dates
R_LIBS_USER so the two concepts are at odds so it's best to make
sure they use the same path. */
+ (NSString*) userLibraryPath {
NSString *archPath = @"";
/* really since 4.1 CRAN R uses R_LIBS_USER set to ~/Library/R/<arch>/<ver>/library
but the mismatch has not been noticed until late so we define the change
officially for R 4.2.0
Since this only affects CRAN version we only set those for x86_64 and arm64
architectures, others will use paths without the arch component. */
#if R_VERSION >= R_Version(4,2,0)
#if __x86_64__
archPath = @"/x86_64";
#elif __arm64__
archPath = @"/arm64";
#endif
#endif
return [[NSString stringWithFormat:@"~/Library/R%@/%@/library", archPath, Rapp_R_version_short] stringByExpandingTildeInPath];
}
- (void) awakeFromNib {
SLog(@"RController.awakeFromNib");
// Add full screen support for MacOSX Lion or higher
[RConsoleWindow setCollectionBehavior:[RConsoleWindow collectionBehavior] | NSWindowCollectionBehaviorFullScreenPrimary];
char *args[5]={ "R", "--no-save", "--no-restore-data", "--gui=aqua", 0 };
requestSaveAction = nil;
sharedRController = self;
currentConsoleWidth = -1;
pendingDocsToOpen = [[NSMutableArray alloc] init];
NSFileManager *fm = [NSFileManager defaultManager];
// Register AppleScript handler for kAEOpenDocuments eventID
[[NSAppleEventManager sharedAppleEventManager] setEventHandler:self
andSelector:@selector(handleAppleEventAEOpenDocuments:withReplyEvent:)
forEventClass:kCoreEventClass
andEventID:kAEOpenDocuments];
[WDirView setToolTip:[NSString stringWithFormat:@"%@ (⌘D)", [WDirView stringValue]]];
[consoleTextView setConsoleMode: YES];
[consoleTextView setEditable:YES];
[consoleTextView setFont:[Preferences unarchivedObjectForKey:RConsoleDefaultFont withDefault:[NSFont fontWithName:@"Monaco" size:11]]];
[consoleTextView setDrawsBackground:NO];
[[consoleTextView enclosingScrollView] setDrawsBackground:NO];
NSMutableDictionary *attr = [NSMutableDictionary dictionary];
[attr setDictionary:[consoleTextView selectedTextAttributes]];
[attr setObject:[Preferences unarchivedObjectForKey:selectionColorKey withDefault:[NSColor colorWithCalibratedRed:0.71f green:0.835f blue:1.0f alpha:1.0f]] forKey:NSBackgroundColorAttributeName];
[consoleTextView setSelectedTextAttributes:attr];
[consoleTextView setNeedsDisplayInRect:[consoleTextView visibleRect]];
NSLayoutManager *lm = [[consoleTextView layoutManager] retain];
#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
[lm setAllowsNonContiguousLayout:YES];
#endif
NSTextStorage *origTS = [[consoleTextView textStorage] retain];
textStorage = [[RConsoleTextStorage alloc] init];
[origTS removeLayoutManager:lm];
[textStorage addLayoutManager:lm];
[lm release];
[origTS release];
[consoleTextView setTextColor:[consoleColors objectAtIndex:iInputColor]];
[consoleTextView setContinuousSpellCheckingEnabled:NO]; // force 'no spell checker'
[[consoleTextView textStorage] setDelegate:self];
RTextView_autoCloseBrackets = [Preferences flagForKey:kAutoCloseBrackets withDefault:YES];
[self setupToolbar];
[RConsoleWindow setOpaque:NO]; // Needed so we can see through it when we have clear stuff on top
[RConsoleWindow setBackgroundColor:[defaultConsoleColors objectAtIndex:iBackgroundColor]]; // we need this, because "update" doesn't touch the color if it's equal - and by default the window has *no* background - not even the default one, so we bring it in sync
[RConsoleWindow setDocumentEdited:YES];
// Force essentially an empty TouchBar due to performance
// problems with Apple's default implemenation
[NSApplication sharedApplication].automaticCustomizeTouchBarMenuItemEnabled = YES;
consoleTextView.touchBar = [self makeTouchBar];
SLog(@" - working directory setup timer");
WDirtimer = [NSTimer scheduledTimerWithTimeInterval:0.5
target:self
selector:@selector(showWorkingDir:)
userInfo:0
repeats:YES];
SLog(@" - load preferences");
[self updatePreferences]; // first update, then add self
[[Preferences sharedPreferences] addDependent: self];
SLog(@" - init R_LIBS");
{ // first initialize R_LIBS if necessary
NSString *prefStr = [Preferences stringForKey:miscRAquaLibPathKey withDefault:nil];
BOOL flag = !isAdmin(); // the default is YES for users and NO for admins
if (prefStr)
flag=[prefStr isEqualToString: @"YES"];
if (flag) {
char *cRLIBS = getenv("R_LIBS");
NSString *addPath = [RController userLibraryPath];
if (![fm fileExistsAtPath:addPath]) { // make sure the directory exists
NSError *err = nil;
[fm createDirectoryAtPath:addPath withIntermediateDirectories:YES attributes:nil error:&err];
if(err != nil) {
NSBeep();
NSLog(@"The directory '%@' couldn't be created!", addPath);
}
}
if (cRLIBS && *cRLIBS)
addPath = [NSString stringWithFormat: @"%s:%@", cRLIBS, addPath];
setenv("R_LIBS", [addPath UTF8String], 1);
SLog(@" - setting R_LIBS=%s", [addPath UTF8String]);
}
}
SLog(@" - set APP VERSION (%s) and REVISION (%@)", R_GUI_VERSION_STR,
[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]);
setenv("R_GUI_APP_VERSION", R_GUI_VERSION_STR, 1);
setenv("R_GUI_APP_REVISION", [(NSString*)[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] UTF8String], 1);
SLog(@" - set R home");
if (!getenv("R_HOME")) {
NSBundle *rfb = [NSBundle bundleWithIdentifier:@"org.r-project.R-framework"];
if (!rfb) {
SLog(@" * problem: R_HOME is not set and I can't find the framework bundle");
if ([fm fileExistsAtPath:@"/Library/Frameworks/R.framework/Resources/bin/R"]) {
SLog(@" * I'm being desperate and I found R at /Library/Frameworks/R.framework - so I'll use it, wish me luck");
setenv("R_HOME", "/Library/Frameworks/R.framework/Resources", 1);
} else
SLog(@" * I didn't even find R framework in the default location, I'm giving up - you're on your own");
} else {
SLog(@" %s", [[rfb resourcePath] UTF8String]);
setenv("R_HOME", [[rfb resourcePath] UTF8String], 1);
}
}
if (getenv("R_HOME"))
home = [[NSString alloc] initWithUTF8String:getenv("R_HOME")];
else
home = [[NSString alloc] initWithString:@""];
{
char tp[1024];
/* since 2.2.0 those are set in the R shell script, so we need to set them as well */
/* FIXME: possible buffer-overflow attack by over-long R_HOME */
if (!getenv("R_INCLUDE_DIR")) {
strcpy(tp, getenv("R_HOME")); strcat(tp, "/include"); setenv("R_INCLUDE_DIR", tp, 1);
}
if (!getenv("R_SHARE_DIR")) {
strcpy(tp, getenv("R_HOME")); strcat(tp, "/share"); setenv("R_SHARE_DIR", tp, 1);
}
if (!getenv("R_DOC_DIR")) {
strcpy(tp, getenv("R_HOME")); strcat(tp, "/doc"); setenv("R_DOC_DIR", tp, 1);
}
}
#if defined __i386__
#define arch_lib_nss @"/lib/i386"
#define arch_str "/i386"
#elif defined __x86_64__
#define arch_lib_nss @"/lib/x86_64"
#define arch_str "/x86_64"
/* not used in R >= 2.15.2, so remove eventually */
#elif defined __ppc__
#define arch_lib_nss @"/lib/ppc"
#define arch_str "/ppc"
#elif defined __ppc64__
#define arch_lib_nss @"/lib/ppc64"
#define arch_str "/ppc64"
#endif
#ifdef arch_lib_nss
if (!getenv("R_ARCH")) {
if ([fm fileExistsAtPath:[[NSString stringWithUTF8String:getenv("R_HOME")] stringByAppendingString: arch_lib_nss]])
setenv("R_ARCH", arch_str, 1);
}
#else
#warning "Unknown architecture, R_ARCH won't be set automatically."
#endif
/* setup LANG variable to match the system locale based on user's CFLocale */
SLog(@" - set locale");
if ([Preferences stringForKey:@"force.LANG"]) {
const char *ls = [[Preferences stringForKey:@"force.LANG"] UTF8String];
if (*ls) {
setenv("LANG", ls, 1);
SLog(@" - force.LANG present, setting LANG to \"%s\"", ls);
} else
SLog(@" - force.LANG present, but empty. LANG won't be set at all.");
} else if ([Preferences flagForKey:@"ignore.system.locale"]==YES) {
setenv("LANG", "en_US.UTF-8", 1);
SLog(@" - ignore.system.locale is set to YES, using en_US.UTF-8");
} else {
char cloc[64];
char *c = getenv("LANG");
cloc[63]=0;
if (c)
strcpy(cloc, c);
else {
CFLocaleRef lr = CFLocaleCopyCurrent();
CFStringRef ls = CFLocaleGetIdentifier(lr);
*cloc=0;
if (ls) {
NSString *lss = (NSString*)ls;
NSRange atr = [lss rangeOfString:@"@"];
SLog(@" CFLocaleGetIdentifier=\"%@\"", ls);
if (atr.location != NSNotFound) {
lss = [lss substringToIndex:atr.location];
SLog(@" - it contains @, stripped to \"%@\"", lss);
}
strncpy(cloc, [lss UTF8String], 63);
}
if (! *cloc) {
SLog(@" CFLocaleGetIdentifier is empty, falling back to en_US.UTF-8");
strcpy(cloc,"en_US.UTF-8");
}
if (lr) CFRelease(lr);
}
if (!strchr(cloc,'.'))
strcat(cloc,".UTF-8");
setenv("LANG", cloc, 1);
SLog(@" - setting LANG=%s", getenv("LANG"));
}
BOOL noReenter = [Preferences flagForKey:@"REngine prevent reentrance"];
if (noReenter == YES) preventReentrance = YES;
SLog(@" - init R");
[[[REngine alloc] initWithHandler:self arguments:args] setCocoaHandler:self];
/* set save action */
[[REngine mainEngine] setSaveAction:[Preferences stringForKey:saveOnExitKey withDefault:@"ask"]];
[[REngine mainEngine] disableRSignalHandlers:[Preferences flagForKey:@"Disable R signal handlers" withDefault:
#ifdef DEBUG_RGUI
YES
#else
NO
#endif
]];
SLog(@" - other widgets");
hist=[[History alloc] init];
BOOL WantThread = ([Preferences flagForKey:@"Redirect stdout/err"] != NO);
SLog(@" - setup stdout/err grabber");
if (WantThread){ // re-route the stdout to our own file descriptor and use ConnectionCache on it
int pfd[2];
pipe(pfd);
dup2(pfd[1], STDOUT_FILENO);
close(pfd[1]);
stdoutFD=pfd[0];
pipe(pfd);
#ifndef PLAIN_STDERR
if ([Preferences flagForKey:@"Ignore stderr"] != YES) {
dup2(pfd[1], STDERR_FILENO);
close(pfd[1]);
}
#endif
stderrFD=pfd[0];
[self addConnectionLog];
}
SLog(@" - set cwd and load history");
[historyView setDoubleAction: @selector(historyDoubleClick:)];
[fm changeCurrentDirectoryPath: [[Preferences stringForKey:initialWorkingDirectoryKey withDefault:@"~"] stringByExpandingTildeInPath]];
if ([Preferences flagForKey:importOnStartupKey withDefault:YES]) {
[self doLoadHistory:nil];
}
SLog(@" - awake is done");
}
- (NSString*) home
{
return home;
}
- (NSString*) currentWorkingDirectory
{
return [[WDirView stringValue] stringByExpandingTildeInPath];
}
-(void) applicationDidFinishLaunching: (NSNotification *)aNotification
{
NSString *fname = nil;
SLog(@"RController:applicationDidFinishLaunching");
SLog(@" - clean up and flush console");
[self flushROutput];
RSEXP *xPT = [[REngine mainEngine] evaluateString:@".Platform$pkgType"];
if (xPT) {
NSString *pkgType = [xPT string];
SLog(@" - pkgType in this R: \"%@\"", pkgType);
if (pkgType) [[PackageInstaller sharedController] setPkgType:pkgType];
[xPT release];
}
SLog(@" - setup notification and timers");
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(RConsoleDidResize:)
name:NSWindowDidResizeNotification
object: RConsoleWindow];
timer = [NSTimer scheduledTimerWithTimeInterval:0.05
target:self
selector:@selector(otherEventLoops:)
userInfo:0
repeats:YES];
Flushtimer = [NSTimer scheduledTimerWithTimeInterval:0.5
target:self
selector:@selector(flushTimerHook:)
userInfo:0
repeats:YES];
// once we're ready with the doc transition, the following will actually fire up the cconsole window
//[[NSDocumentController sharedDocumentController] openUntitledDocumentOfType:@"Rcommand" display:YES];
fname = [[[[NSFileManager defaultManager] currentDirectoryPath] stringByAppendingString: @"/.RData"] stringByExpandingTildeInPath];
if (([pendingDocsToOpen count] == 0) &&
([[NSFileManager defaultManager] fileExistsAtPath: fname])) {
[[REngine mainEngine] executeString: [NSString stringWithFormat:@"load(\"%@\")", fname]];
[self handleWriteConsole: [NSString stringWithFormat:@"%@%@]\n", NLS(@"[Workspace restored from "), fname]];
SLog(@"RController.applicationDidFinishLaunching - load workspace %@", fname);
}
fname = [[Preferences stringForKey:historyFileNamePathKey withDefault: @".Rapp.history"] stringByExpandingTildeInPath];
if ([Preferences flagForKey:importOnStartupKey withDefault:YES] && ([[NSFileManager defaultManager] fileExistsAtPath: fname])) {
NSString *fullfname = [NSString stringWithString:fname];
if ([fname characterAtIndex:0] != '/') {
fullfname = [[[[[NSFileManager defaultManager] currentDirectoryPath]
stringByAppendingString:@"/"] stringByAppendingString: fname]
stringByExpandingTildeInPath];
}
[self handleWriteConsole: [NSString stringWithFormat:@"%@%@]\n\n", NLS(@"[History restored from "), fullfname]];
SLog(@"RController.applicationDidFinishLaunching - load history file %@", fname);
}
SLog(@"RController.openDocumentsPending: process pending 'odoc' events");
if ([pendingDocsToOpen count] > 0) {
NSEnumerator *enumerator = [pendingDocsToOpen objectEnumerator];
NSString *fileName;
SLog(@" - %d documents to open", [pendingDocsToOpen count]);
while ((fileName = (NSString*) [enumerator nextObject]))
[self application:NSApp openFile:fileName];
[pendingDocsToOpen removeAllObjects];
}
[[REngine mainEngine] executeString:@"if (exists('.First') && is.function(.First) && !identical(.First, .__RGUI__..First)) .First()"];
SLog(@" - set Quartz preferences (if necessary)");
BOOL flag=[Preferences flagForKey:useQuartzPrefPaneSettingsKey withDefault: NO];
if (flag) {
NSString *qWidth = [Preferences stringForKey:quartzPrefPaneWidthKey withDefault: @"5"];
NSString *qHeight = [Preferences stringForKey:quartzPrefPaneHeightKey withDefault: @"5"];
NSString *qDPI = [Preferences stringForKey:quartzPrefPaneDPIKey withDefault: @""];
[[REngine mainEngine] executeString:[NSString stringWithFormat:@"quartz.options(width=%@,height=%@,dpi=%@)", qWidth, qHeight, ([qDPI length] == 0) ? @"NA_real_" : qDPI]];
}
appLaunched = YES;
[self setStatusLineText:@""];
{
// check locale
RSEXP * x = [[REngine mainEngine] evaluateString:@"Sys.getlocale()"];
if (x) {
NSString *s = [x string];
if (s) {
NSRange r = [s rangeOfString:@"utf" options:NSCaseInsensitiveSearch];
if (r.location == NSNotFound) {
[self writeConsoleDirectly:NLS(@"WARNING: You're using a non-UTF8 locale, therefore only ASCII characters will work.\nPlease read R for Mac OS X FAQ (see Help) section 9 and adjust your system preferences accordingly.\n") withColor:[NSColor redColor]];
}
}
[x release];
}
}
[self updateReInterpretEncodingMenu];
// for some reason Cocoa never calls this so we have to do it by hand even though it's internal
// FIXME: check with OS X version to make sure this doesn't go away
if ([[NSDocumentController sharedDocumentController] respondsToSelector:@selector(_autoreopenDocuments)]) {
SLog(@" - re-open autosaved documents (if any)");
[(NSDocumentControllerWithAutosave*)[NSDocumentController sharedDocumentController] _autoreopenDocuments];
} else {
SLog(@"WARNING: _autoreopenDocuments is not supported, cannot re-open autosaved documents");
}
[self performSelector:@selector(setOptionWidth:) withObject:nil afterDelay:0.0];
SLog(@" - done, ready to go");
// Register us as service provider
[NSApp setServicesProvider:self];
if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6) {
NSString *label = nil;
if(([[self window] styleMask] & NSFullScreenWindowMask) == NSFullScreenWindowMask)
label = NLS(@"Exit Full Screen");
else
label = NLS(@"Enter Full Screen");
toggleFullScreenMenuItem = [[NSMenuItem alloc] initWithTitle:label action:@selector(toggleFullScreenMode:) keyEquivalent:@"f"];
[toggleFullScreenMenuItem setKeyEquivalentModifierMask:(NSControlKeyMask | NSCommandKeyMask)];
NSInteger m = [[NSApp mainMenu] numberOfItems]-2; // Window submenu
[[[[NSApp mainMenu] itemAtIndex:m] submenu] insertItem:[NSMenuItem separatorItem] atIndex:0];
[[[[NSApp mainMenu] itemAtIndex:m] submenu] insertItem:toggleFullScreenMenuItem atIndex:0];
} else {
// <TODO> folding only for >=10.7 - why?
[[[[[NSApp mainMenu] itemAtIndex:3] submenu] itemAtIndex:9] setHidden:YES];
[[[[[NSApp mainMenu] itemAtIndex:3] submenu] itemAtIndex:10] setHidden:YES];
}
SLog(@"RController.applicationDidFinishLaunching - show main window");
}
- (void)windowDidEnterFullScreen:(NSNotification *)notification
{
if(toggleFullScreenMenuItem)
[toggleFullScreenMenuItem setTitle:NLS(@"Exit Full Screen")];
}
- (void)windowDidExitFullScreen:(NSNotification *)notification
{
if(toggleFullScreenMenuItem)
[toggleFullScreenMenuItem setTitle:NLS(@"Enter Full Screen")];
}
-(IBAction)toggleFullScreenMode:(id)sender
{
#if !defined(MAC_OS_X_VERSION_10_7) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
[[self window] toggleFullScreen:nil];
#endif
}
- (void)updateReInterpretEncodingMenu
{
// Update Re-Open with Encoding submenu
while ([reinterpretEncodingMenu numberOfItems]) [reinterpretEncodingMenu removeItemAtIndex:0];
NSArray *enabledEncodings = [[RChooseEncodingPopupAccessory sharedInstance] enabledEncodings];
NSInteger i;
NSMenuItem *encItem;
for(i=0; i<[enabledEncodings count]; i++) {
encItem = [[NSMenuItem alloc] initWithTitle:[NSString localizedNameOfStringEncoding:[[enabledEncodings objectAtIndex:i] unsignedIntValue]] action:@selector(reInterpretDocument:) keyEquivalent:@""];
[encItem setRepresentedObject:[enabledEncodings objectAtIndex:i]];
[reinterpretEncodingMenu addItem:encItem];
[encItem release];
}
[reinterpretEncodingMenu addItem:[NSMenuItem separatorItem]];
encItem = [[NSMenuItem alloc] initWithTitle:NLS(@"Customize List…") action:@selector(customizeEncodingList:) keyEquivalent:@""];
[reinterpretEncodingMenu addItem:encItem];
[encItem release];
}
- (BOOL)appLaunched {
return appLaunched;
}
-(void) addConnectionLog
{
NSPort *port1;
NSPort *port2;
NSArray *portArray;
NSConnection *connectionToTransferServer;
port1 = [NSPort port];
port2 = [NSPort port];
connectionToTransferServer = [[NSConnection alloc] initWithReceivePort:port1 sendPort:port2];
[connectionToTransferServer setRootObject:self];
portArray = [NSArray arrayWithObjects:port2, port1, nil];
[NSThread detachNewThreadSelector:@selector(readThread:)
toTarget:self
withObject:portArray];
}
- (void) readThread: (NSArray *)portArray
{
NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
NSConnection *connectionToController;
RController *rc = nil;
unsigned int bufSize=2048;
char *buf=(char*) malloc(bufSize+16);
int n=0, pib=0, flushMark=bufSize-(bufSize>>2);
int bufFD=0;
fd_set readfds;
struct timeval timv;
BOOL truncated = NO;
timv.tv_sec=0; timv.tv_usec=300000; /* timeout */
connectionToController = [NSConnection connectionWithReceivePort:[portArray objectAtIndex:0]
sendPort:[portArray objectAtIndex:1]];
rc = ((RController *)[connectionToController rootProxy]);
// set timeouts only *after* the connection was established
[connectionToController setRequestTimeout:2.0];
[connectionToController setReplyTimeout:2.0];
fcntl(stdoutFD, F_SETFL, O_NONBLOCK);
fcntl(stderrFD, F_SETFL, O_NONBLOCK);
while (1) {
int selr=0, maxfd=stdoutFD;
int validRootFD=-1;
FD_ZERO(&readfds);
FD_SET(stdoutFD,&readfds);
FD_SET(stderrFD,&readfds); if(stderrFD>maxfd) maxfd=stderrFD;
if (rootFD!=-1) {
validRootFD = rootFD; // we copy it as to not run into threading problems when it is changed while we're in the middle of processing
FD_SET(rootFD,&readfds);
if(rootFD>maxfd) maxfd=rootFD;
}
selr=select(maxfd+1, &readfds, 0, 0, &timv);
if (FD_ISSET(stdoutFD, &readfds)) {
if (bufFD!=0 && pib>0) {
@try{
[rc writeLogsWithBytes:buf length:pib type:bufFD];
if (truncated) { [rc writeLogsWithBytes:"\n(WARNING: partial output only, ask package author to use Rprintf instead!)\n" length:-1 type:1]; truncated=NO; }
} @catch(NSException *ex) {
truncated = YES;
}
pib=0;
}
bufFD=0;
while (pib<bufSize && (n=read(stdoutFD,buf+pib,bufSize-pib))>0)
pib+=n;
if (pib>flushMark) { // if we reach the flush mark, dump it
@try{
[rc writeLogsWithBytes:buf length:pib type:bufFD];
if (truncated) { [rc writeLogsWithBytes:"\n(WARNING: partial output only, ask package author to use Rprintf instead!)\n" length:-1 type:1]; truncated=NO; }
} @catch(NSException *ex) {
truncated = YES;
}
pib=0;
}
}
if (FD_ISSET(stderrFD, &readfds)) {
if (bufFD!=1 && pib>0) {
@try {
[rc writeLogsWithBytes:buf length:pib type:bufFD];
} @catch(NSException *ex) {
}
pib=0;
}
bufFD=1;
while (pib<bufSize && (n=read(stderrFD,buf+pib,bufSize-pib))>0)
pib+=n;
if (pib>flushMark) { // if we reach the flush mark, dump it
@try{
[rc writeLogsWithBytes:buf length:pib type:bufFD];
} @catch(NSException *ex) {
}
pib=0;
}
}
if (validRootFD!=-1 && FD_ISSET(validRootFD, &readfds)) {
if (bufFD!=2 && pib>0) {
@try{
[rc writeLogsWithBytes:buf length:pib type:bufFD];
} @catch(NSException *ex) {
truncated = YES;
}
pib=0;
}
bufFD=2;
while (pib<bufSize && (n=read(validRootFD,buf+pib,bufSize-pib))>0)
pib+=n;
if (n==0 || pib>flushMark) { // if we reach the flush mark, dump it
@try{
[rc writeLogsWithBytes:buf length:pib type:bufFD];
} @catch(NSException *ex) {
truncated = YES;
}
pib=0;
}
if (n==0) rootFD=-1; // we indicate EOF on the rootFD by setting it to -1
}
if ((forceStdFlush || selr==0) && pib>0) { // dump also if we got a timeout
@try{
[rc writeLogsWithBytes:buf length:pib type:bufFD];
} @catch(NSException *ex) {
truncated = YES;
}
pib=0;
}
}
free(buf);
[pool release];
}
- (void) flushStdConsole
{
fflush(stderr);
fflush(stdout);
forceStdFlush=YES;
}
- (void) addChildProcess: (pid_t) pid
{
childPID=pid;
if (pid>0 && toolbarStopItem) [toolbarStopItem setEnabled:YES];
}
- (void) rmChildProcess: (pid_t) pid
{
childPID=0;
if (!busyRFlag && toolbarStopItem) [toolbarStopItem setEnabled:NO];
[self flushStdConsole];
}
- (void)ignoreMagnifyingEventTimer
{
ignoreMagnifyingEvent = NO;
}
- (void) fontSizeChangedBy:(float)delta withSender:(id)sender
{
SLog(@"RController - fontSizeChangedBy:%f", delta);
NSFont *font;
id firstResponder = [[NSApp keyWindow] firstResponder];
// Check if first responder is a WebView
if([[[firstResponder class] description] isEqualToString:@"WebHTMLView"]) {
// Try to get the corresponding WebView
id aWebFrameView = [[[firstResponder superview] superview] superview];
if(aWebFrameView && [aWebFrameView respondsToSelector:@selector(webFrame)]) {
WebView *aWebView = [[(WebFrameView*)aWebFrameView webFrame] webView];
if(aWebView) {
if(!ignoreMagnifyingEvent) {
// delay font size changing for 200msecs
ignoreMagnifyingEvent = YES;
[self performSelector:@selector(ignoreMagnifyingEventTimer) withObject:nil afterDelay:0.2f];
if(delta > 0)
[aWebView makeTextLarger:sender];
else if(delta < 0)
[aWebView makeTextSmaller:sender];
}
}
}
}
// Change size for RConsole
else if ([RConsoleWindow isKeyWindow]) {
font = [[NSFontPanel sharedFontPanel] panelConvertFont:[NSUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] dataForKey:RConsoleDefaultFont]]];
float s = [font pointSize];
s = s + delta;
font = [NSFont fontWithName:[font fontName] size:s];
if(font) {
[[NSUserDefaults standardUserDefaults] setObject:[NSArchiver archivedDataWithRootObject:font] forKey:RConsoleDefaultFont];
[consoleTextView setFont:font];
// Force to scroll view to cursor
[consoleTextView scrollRangeToVisible:[consoleTextView selectedRange]];
}
[[consoleTextView textStorage] setFont:font];
[self setOptionWidth:YES];
}
// Change size in R script windows
else if ([firstResponder isKindOfClass:[RScriptEditorTextView class]]) {