-
Notifications
You must be signed in to change notification settings - Fork 8
/
RDocument.m
867 lines (697 loc) · 29.4 KB
/
RDocument.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
/*
* R.app : a Cocoa front end to: "R A Computer Language for Statistical Data Analysis"
*
* R.app Copyright notes:
* Copyright (C) 2004-5 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.
*/
#import "RGUI.h"
#import "RDocument.h"
#import "RDocumentController.h"
#import "RDocumentWinCtrl.h"
#import "RController.h"
#import "Preferences.h"
#import "RChooseEncodingPopupAccessory.h"
#import "REngine.h"
#import "HelpManager.h"
#import "NSString_RAdditions.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
@implementation RDocument
- (id)init
{
self = [super init];
if (self) {
SLog(@"RDocument(%@) init", self);
documentEncoding = NSUTF8StringEncoding;
initialContents=nil;
initialContentsType=nil;
isEditable=YES;
isREdit=NO;
myWinCtrl=nil;
rdToolsAreWorking=NO;
fileTypeWasChangedWhileSaving = NO;
}
return self;
}
- (void)close {
SLog(@"RDocument.close <%@> (wctrl=%@)", self, myWinCtrl);
if (initialContents) [initialContents release], initialContents=nil;
if (initialContentsType) [initialContentsType release], initialContentsType=nil;
if (myWinCtrl) {
SLog(@" - window: %@", [myWinCtrl window]);
[self removeWindowController:myWinCtrl];
[myWinCtrl close];
// --- something is broken - winctrl close doesn't work - I have no idea why - this is a horrible hack to cover up
//NSWindow *w = [myWinCtrl window];
//if (w) [NSApp removeWindowsItem: w];
//[[(RDocumentController*)[NSDocumentController sharedDocumentController] walkKeyListBack] makeKeyAndOrderFront:self];
// --- end of hack
[myWinCtrl release];
myWinCtrl=nil;
}
[super close];
}
- (void)dealloc {
if (myWinCtrl) [self close];
[super dealloc];
}
// FIXME: I don't like this - we should use common text storage instead; conceptually textView is NOT the storage part
- (NSTextView *)textView {
return [myWinCtrl textView];
}
- (void) makeWindowControllers {
SLog(@"RDocument.makeWindowControllers: creating RDocumentWinCtrl");
if (myWinCtrl) {
SLog(@"*** RDocument.makeWindowControllers: my assumption is that I have only one win controller, but I already have %@! I'll autorelease the first one but won't detach it - don't blame me if this crashes...", myWinCtrl);
[myWinCtrl autorelease];
}
// create RDocumentWinCtrl which is a window controller - it loads the corresponding NIB and sets up the window
myWinCtrl = [[RDocumentWinCtrl alloc] initWithWindowNibName:@"RDocument"];
[self addWindowController:myWinCtrl];
}
- (NSString*)windowNibName
{
return @"RDocument";
}
- (int) fileEncoding
{
return (int) documentEncoding;
}
- (void) setFileEncoding: (int) encoding
{
SLog(@" - setFileEncoding: %d", encoding);
documentEncoding = (NSStringEncoding) encoding;
}
- (void)didSaveSelector
{
// Reopen file if file type was changed while saving
if(fileTypeWasChangedWhileSaving) {
NSError *theError = nil;
fileTypeWasChangedWhileSaving = NO;
[myWinCtrl close];
[[NSDocumentController sharedDocumentController] openDocumentWithContentsOfURL:[self fileURL] display:YES error:&theError];
if (theError) {
NSLog(@"*** openDocumentWithContentsOfURL: failed with %@", theError);
NSBeep();
}
return;
}
// Remain focus on current document after closing SaveAs panel
[[myWinCtrl window] makeKeyWindow];
encodingPopUp = nil;
}
- (void)runModalSavePanelForSaveOperation:(NSSaveOperationType)saveOperation delegate:(id)delegate didSaveSelector:(SEL)didSaveSelector contextInfo:(void *)contextInfo
{
// dispatch didSaveSelector: in order to remain input focus to current document
[super runModalSavePanelForSaveOperation:saveOperation delegate:self didSaveSelector:@selector(didSaveSelector) contextInfo:contextInfo];
}
// customize Save panel by adding "encoding" view for R documents
- (BOOL)prepareSavePanel:(NSSavePanel *)savePanel
{
if([[self fileType] isEqualToString:ftRSource]) {
[savePanel setAllowedFileTypes:[NSArray arrayWithObject:@"R"]];
if (myWinCtrl)
[savePanel setAccessoryView:[[[NSDocumentController sharedDocumentController] class] encodingAccessory:(NSStringEncoding)documentEncoding
includeDefaultEntry:NO
encodingPopUp:&encodingPopUp]];
if(encodingPopUp) [encodingPopUp setEnabled:YES];
[savePanel setAllowsOtherFileTypes:YES];
}
else if([[self fileType] isEqualToString:ftRdDoc]) {
[savePanel setAllowedFileTypes:[NSArray arrayWithObject:@"Rd"]];
if (myWinCtrl)
[savePanel setAccessoryView:[[[NSDocumentController sharedDocumentController] class] encodingAccessory:(NSStringEncoding)documentEncoding
includeDefaultEntry:NO
encodingPopUp:&encodingPopUp]];
if(encodingPopUp) [encodingPopUp setEnabled:YES];
[savePanel setAllowsOtherFileTypes:YES];
}
else if(initialContentsType && [initialContentsType hasSuffix:@".rtf"]) {
[savePanel setAllowedFileTypes:[NSArray arrayWithObject:@"rtf"]];
[savePanel setAllowsOtherFileTypes:NO];
[savePanel setAccessoryView:nil];
}
[savePanel setCanSelectHiddenExtension:YES];
return YES;
}
- (BOOL)writeToURL:(NSURL *)absoluteURL ofType:(NSString *)docType error:(NSError **)outError
{
SLog(@"RDocument.writeToFile: %@ ofType: %@ ", absoluteURL, docType);
NSString *oldFileType = (initialContentsType)?:ftRSource;
if([[[absoluteURL absoluteString] lowercaseString] hasSuffix:@".rtf"]) {
SLog(@" - docType was changed to rtf due to file extension");
if(initialContentsType) [initialContentsType release], initialContentsType = nil;
initialContentsType = [[NSString stringWithString:@"public.rtf"] retain];
}
else if([[[absoluteURL absoluteString] lowercaseString] hasSuffix:@".rd"]) {
SLog(@" - docType was changed to Rd due to file extension");
if(initialContentsType) [initialContentsType release], initialContentsType = nil;
initialContentsType = [[NSString stringWithString:ftRdDoc] retain];
[self setFileType:ftRdDoc];
}
else {
if(initialContentsType) [initialContentsType release], initialContentsType = nil;
initialContentsType = [[NSString stringWithString:ftRSource] retain];
[self setFileType:ftRSource];
}
SLog(@" - used docType %@", (initialContentsType)?:ftRSource);
fileTypeWasChangedWhileSaving = ([initialContentsType isEqualToString:oldFileType]) ? NO : YES;
return [super writeToURL:absoluteURL ofType:(initialContentsType)?:ftRSource error:outError];
}
- (void) loadInitialContents
{
if (!initialContents) {
SLog(@"RDocument.loadInitialContents: empty contents, skipping");
return;
}
SLog(@"RDocument.loadInitialContents: loading");
NSEnumerator *e = [[self windowControllers] objectEnumerator];
RDocumentWinCtrl *wc = nil;
while ((wc = (RDocumentWinCtrl*)[e nextObject])) {
if ([initialContentsType hasSuffix:@".rtf"]) {
SLog(@" - new RTF contents (%d bytes) for window controller %@", [initialContents length], wc);
[wc replaceContentsWithRtf: initialContents];
} else {
const unsigned char *ic = [initialContents bytes];
NSString *cs;
SLog(@" - try to auto-detect file encoding");
documentEncoding = NSUTF8StringEncoding;
if ([initialContents length] > 1
&& ((ic[0] == 0xff && ic[1] == 0xfe) || (ic[0] == 0xfe && ic[1] == 0xff))) // Unicode BOM
documentEncoding = NSUnicodeStringEncoding;
cs = [[NSString alloc] initWithData:initialContents encoding:documentEncoding];
if(!cs && [self fileURL]) {
SLog(@" - failed to load as %d encoding, try to autodetect via initWithContentsOfURL:documentEncoding:error:", documentEncoding);
cs = [[NSString alloc] initWithContentsOfURL:[self fileURL] usedEncoding:&documentEncoding error:nil];
}
if (!cs) { // fall back to Latin1 since it's widely used
SLog(@" - failed to load as %d encoding, falling back to Latin1", documentEncoding);
documentEncoding = NSISOLatin1StringEncoding;
cs = [[NSString alloc] initWithData:initialContents encoding:documentEncoding];
}
if (!cs) { // fall back to MacRoman - old default
SLog(@" - failed to load as %d encoding, falling back to MacRoman", documentEncoding);
documentEncoding = NSMacOSRomanStringEncoding;
cs = [[NSString alloc] initWithData:initialContents encoding:documentEncoding];
}
if (cs) {
SLog(@" - new string contents (%d chars) for window controller %@", [cs length], wc);
// Important! otherwise the save box won't know
[wc setFileEncoding:documentEncoding];
if(![initialContentsType isEqualToString:ftRSource] && ![initialContentsType isEqualToString:ftRdDoc]) {
SLog(@" - set plain text mode");
[wc setPlain:YES];
}
[wc replaceContentsWithString:cs];
}
[cs release];
}
}
// release initialContents to clean heap esp. for large files
if(initialContents) [initialContents release], initialContents=nil;
}
- (BOOL)revertToContentsOfURL:(NSURL *)absoluteURL ofType:(NSString *)typeName error:(NSError **)outError
{
SLog(@"RDocument:revertToContentsOfURL %@ of type %@", absoluteURL, typeName);
if([typeName hasSuffix:@".rtf"]) {
NSData *cs = [[NSData alloc] initWithContentsOfURL:absoluteURL];
if(cs) {
[myWinCtrl replaceContentsWithRtf:cs];
[cs release];
// Remain focus
[[myWinCtrl window] makeKeyWindow];
// Clear edited status
[self updateChangeCount:NSChangeCleared];
return YES;
}
} else {
NSString *cs = [[NSString alloc] initWithContentsOfURL:absoluteURL encoding:documentEncoding error:nil];
if(cs) {
[myWinCtrl replaceContentsWithString:cs];
[cs release];
// Remain focus
[[myWinCtrl window] makeKeyWindow];
// Clear edited status
[self updateChangeCount:NSChangeCleared];
return YES;
}
}
SLog(@" - couldn't revert document");
NSBeginAlertSheet(NLS(@"Reverting Document"), NLS(@"OK"), nil, nil,
[myWinCtrl window], self,
@selector(sheetDidEnd:returnCode:contextInfo:), nil, nil,
NLS(@"Couldn't revert to saved document"));
outError = nil;
return YES;
}
- (void) reinterpretInEncoding: (NSStringEncoding) encoding
{
SLog(@"RDocument:reinterpretInEncoding - new encoding: %ld", encoding);
NSString *sc = [myWinCtrl contentsAsString];
NSData *data = [sc dataUsingEncoding:documentEncoding allowLossyConversion:YES];
if(!data) {
NSBeginAlertSheet(NLS(@"Convertion Error"), NLS(@"OK"), nil, nil,
[myWinCtrl window], self,
@selector(sheetDidEnd:returnCode:contextInfo:), nil, nil,
[NSString stringWithFormat:@"%@ %@", NLS(@"Couldn't reinterpret the text by using the encoding"),
[NSString localizedNameOfStringEncoding:encoding]]);
SLog(@"- can't get data");
return;
}
NSString *ns = [[NSString alloc] initWithData:data encoding:encoding];
if (!ns) {
[ns release];
NSBeginAlertSheet(NLS(@"Convertion Error"), NLS(@"OK"), nil, nil,
[myWinCtrl window], self,
@selector(sheetDidEnd:returnCode:contextInfo:), nil, nil,
[NSString stringWithFormat:@"%@ %@", NLS(@"Couldn't reinterpret the text by using the encoding"),
[NSString localizedNameOfStringEncoding:encoding]]);
SLog(@" - can't create string");
return;
}
// Check for any non-valid (surrogate issues esp. if UTF16 is chosen)
if ([ns UTF8String] == NULL) {
[ns release];
NSBeginAlertSheet(NLS(@"Convertion Error"), NLS(@"OK"), nil, nil,
[myWinCtrl window], self,
@selector(sheetDidEnd:returnCode:contextInfo:), nil, nil,
[NSString stringWithFormat:@"%@ %@", NLS(@"Couldn't reinterpret the text by using the encoding"),
[NSString localizedNameOfStringEncoding:encoding]]);
SLog(@" - string contains invalid bytes for chosen encoding");
return;
}
documentEncoding = encoding;
[myWinCtrl setFileEncoding:documentEncoding];
// replace text in such a way that the user can perform undo:
[[myWinCtrl textView] selectAll:nil];
[[myWinCtrl textView] insertText:ns];
[ns release];
}
- (NSData *)dataRepresentationOfType:(NSString *)aType
{
if(encodingPopUp) {
[[NSUserDefaults standardUserDefaults] setInteger:[[[encodingPopUp selectedItem] representedObject] unsignedIntegerValue] forKey:lastUsedFileEncoding];
documentEncoding = (NSStringEncoding)[[[encodingPopUp selectedItem] representedObject] unsignedIntegerValue];
}
encodingPopUp = nil;
// Insert code here to write your document from the given data. You can also choose to override -fileWrapperRepresentationOfType: or -writeToFile:ofType: instead.
NSEnumerator *e = [[self windowControllers] objectEnumerator];
RDocumentWinCtrl *wc = nil;
while ((wc = (RDocumentWinCtrl*)[e nextObject])) {
if([aType hasSuffix:@".rtf"])
return [wc contentsAsRtf];
else
return [[wc contentsAsString] dataUsingEncoding: documentEncoding];
}
return nil;
}
/* This method is implemented to allow image data file to be loaded into R using open
or drag and drop. In case of a successfull loading of image file, we don't want to
create the UI for the document.
*/
- (BOOL)readFromFile:(NSString *)fileName ofType:(NSString *)docType{
if( [docType isEqual:@"R Data File"] || [[RController sharedController] isImageData:fileName] == 0){
[[RController sharedController] sendInput: [NSString stringWithFormat:@"load(\"%@\")",fileName]];
// [[NSDocumentController sharedDocumentController] setShouldCreateUI:NO];
return(YES);
} else {
// [[NSDocumentController sharedDocumentController] setShouldCreateUI:YES];
return( [super readFromFile: fileName ofType: docType] );
}
}
- (BOOL) loadDataRepresentation: (NSData *)data ofType:(NSString *)aType{
if (initialContents) [initialContents release], initialContents=nil;
if (initialContentsType) [initialContentsType release], initialContentsType = nil;
initialContentsType = [[NSString alloc] initWithString:aType];
initialContents = [data retain];
SLog(@"RDocument.loadDataRepresentation loading %d bytes of data and docType %@", [data length], initialContentsType);
return YES;
}
+ (void) changeDocumentTitle: (NSDocument *)document Title:(NSString *)title{
NSEnumerator *e = [[document windowControllers] objectEnumerator];
NSWindowController *wc = nil;
while ((wc = [e nextObject])) {
NSWindow *dw = [wc window];
[dw setTitle: title];
}
}
- (void) setEditable: (BOOL) editable
{
isEditable=editable;
NSEnumerator *e = [[self windowControllers] objectEnumerator];
RDocumentWinCtrl *wc = nil;
while ((wc = (RDocumentWinCtrl*)[e nextObject]))
[wc setEditable: editable];
}
- (BOOL) editable
{
return isEditable;
}
- (void) setREditFlag: (BOOL) flag
{
isREdit=flag;
}
- (BOOL) hasREditFlag
{
return isREdit;
}
- (NSString *)displayName
{
if(isREdit) return NLS(@"Object Editor");
return [super displayName];
}
- (BOOL) isRTF
{
return (([self fileName] && [[[self fileName] lowercaseString] hasSuffix:@".rtf"]) || ([self fileType] && [[self fileType] hasSuffix:@".rtf"]));
}
- (BOOL) checkRdDocumentWithFilePath:(NSString*)inputFile reportSuccess:(BOOL)reportSuccess
{
[myWinCtrl setStatusLineText:[NSString stringWithFormat:@"%@ (%@)", NLS(@"Check Rd document…"), NLS(@"press ⌘. to cancel")]];
NSError *error = nil;
[[[myWinCtrl textView] string] writeToFile:inputFile atomically:YES encoding:NSUTF8StringEncoding error:&error];
if(error != nil){
NSBeep();
NSLog(@"RDocument.checkRdDocument couldn't save a temporary file");
[myWinCtrl setStatusLineText:@""];
return NO;
}
NSString *convCmd = [NSString stringWithFormat:@"R --vanilla -q --slave --encoding=UTF-8 -e 'tools:::checkRd(\"%@\")'", inputFile];
NSError *bashError = nil;
NSString *errMessage = [convCmd evaluateAsBashCommandAndError:&bashError];
if(bashError != nil) {
if([bashError code] == 1) {
errMessage = [NSString stringWithFormat:@"%@%@%@", errMessage, ([errMessage length])?@"\n":@"", [[bashError userInfo] objectForKey:NSLocalizedDescriptionKey]];
} else {
NSBeep();
NSLog(@"RDocument.checkRdDocument bailed due to BASH error:\n%@", bashError);
[myWinCtrl setStatusLineText:@""];
return NO;
}
}
NSInteger errorMessageMaxLength = 900;
if(![errMessage length])
errMessage = (reportSuccess) ? NLS(@"Check was successful.") : @"";
else {
errMessage = [errMessage stringByReplacingOccurrencesOfString:inputFile withString:NLS(@"Rd file")];
errMessage = [errMessage stringByReplacingOccurrencesOfString:[inputFile lastPathComponent] withString:NLS(@"Rd file")];
}
if(![errMessage length]) {
[myWinCtrl setStatusLineText:@""];
return YES;
}
if([errMessage length] > errorMessageMaxLength)
errMessage = [[errMessage substringWithRange:NSMakeRange(0,errorMessageMaxLength)] stringByAppendingString:@"\n…"];
NSArray *errorLines = [errMessage componentsMatchedByRegex:[NSString stringWithFormat:@"%@:\\s*\\(?(\\d+)(\\)|-)?\\s*:?", NLS(@"Rd file")] capture:1L];
// Find first error line number since checkRd messages are appended and in
// most cases more precise
NSInteger errorLineNumber = -1;
if([errorLines count]) {
NSInteger i;
NSInteger firstErrorLine = 10000000;
NSInteger anErrorLine;
for(i=0; i<[errorLines count]; i++) {
anErrorLine = [(NSString*)[errorLines objectAtIndex:i] integerValue];
if(anErrorLine > 0 && (anErrorLine < firstErrorLine))
firstErrorLine = anErrorLine;
}
errorLineNumber = firstErrorLine;
}
[myWinCtrl setStatusLineText:@""];
NSAlert *alert = [NSAlert alertWithMessageText:NLS(@"Rd Check")
defaultButton:NLS(@"OK")
alternateButton:nil
otherButton:nil
informativeTextWithFormat:errMessage];
[alert setAlertStyle:NSWarningAlertStyle];
[alert runModal];
[[myWinCtrl window] makeKeyAndOrderFront:self];
[[myWinCtrl window] makeFirstResponder:[myWinCtrl textView]];
if(errorLineNumber >=0) {
NSRange currentLineRange = NSMakeRange(0, 0);
NSString *s = [[[myWinCtrl textView] textStorage] string];
NSInteger lineCounter = 0;
while(lineCounter++ < errorLineNumber)
currentLineRange = [s lineRangeForRange:NSMakeRange(NSMaxRange(currentLineRange), 0)];
SLog(@" - go to error line number %d", errorLineNumber);
// select found line
[[myWinCtrl textView] setSelectedRange:currentLineRange];
// scroll to found line
[[myWinCtrl textView] centerSelectionInVisibleArea:nil];
// remove selection after 500ms
[[myWinCtrl textView] performSelector:@selector(moveLeft:) withObject:nil afterDelay:0.5];
}
return NO;
}
- (BOOL) checkRdDocument
{
if(rdToolsAreWorking) return NO;
rdToolsAreWorking = YES;
NSString *tempName = [NSTemporaryDirectory() stringByAppendingPathComponent: [NSString stringWithFormat: @"%.0f.", [NSDate timeIntervalSinceReferenceDate] * 1000.0]];
NSString *inputFile = [NSString stringWithFormat: @"%@%@", tempName, @"rd"];
BOOL success = [self checkRdDocumentWithFilePath:inputFile reportSuccess:YES];
[[NSFileManager defaultManager] removeItemAtPath:inputFile error:NULL];
rdToolsAreWorking = NO;
return success;
}
- (void) insertRdDataTemplate
{
if(rdToolsAreWorking) return;
rdToolsAreWorking = YES;
[myWinCtrl setStatusLineText:[NSString stringWithFormat:@"%@", NLS(@"press ⌘. to cancel")]];
NSError *bashError = nil;
NSString *templateStr = [@"R --vanilla --slave -e 'cat(unlist(prompt(Formaldehyde,NA)), sep=\"§\")'" evaluateAsBashCommandAndError:&bashError];
[myWinCtrl setStatusLineText:@""];
if(bashError != nil) {
NSBeep();
NSLog(@"RDocumentWinCtrl.insertRdDataTemplate bailed due to BASH error:\n%@", bashError);
rdToolsAreWorking = NO;
return;
}
if(!templateStr) {
NSBeep();
NSLog(@"RDocumentWinCtrl.insertRdDataTemplate bailed; no response from called R session");
rdToolsAreWorking = NO;
return;
}
templateStr = [templateStr stringByReplacingOccurrencesOfString:@"§" withString:@"\n"];
templateStr = [templateStr stringByReplacingOccurrencesOfString:@"Formaldehyde" withString:NLS(@"DATA_NAME")];
templateStr = [templateStr stringByReplacingOccurrencesOfString:@"carb" withString:NLS(@"VAR_NAME_1")];
templateStr = [templateStr stringByReplacingOccurrencesOfString:@"optden" withString:NLS(@"VAR_NAME_2")];
[[myWinCtrl textView] insertText:templateStr];
NSRange newFunRange = [templateStr rangeOfString:NLS(@"DATA_NAME")];
[[myWinCtrl textView] setSelectedRange:newFunRange];
[[myWinCtrl textView] scrollRangeToVisible:newFunRange];
rdToolsAreWorking = NO;
}
- (void) insertRdFunctionTemplate
{
if(rdToolsAreWorking) return;
rdToolsAreWorking = YES;
[myWinCtrl setStatusLineText:[NSString stringWithFormat:@"%@", NLS(@"press ⌘. to cancel")]];
NSError *bashError = nil;
NSString *templateStr = [@"R --vanilla --slave -e 'cat(unlist(prompt(mean.POSIXct,NA)), sep=\"§\")'" evaluateAsBashCommandAndError:&bashError];
[myWinCtrl setStatusLineText:@""];
if(bashError != nil) {
NSBeep();
NSLog(@"RDocumentWinCtrl.insertRdFunctionTemplate bailed due to BASH error:\n%@", bashError);
rdToolsAreWorking = NO;
return;
}
if(!templateStr) {
NSBeep();
NSLog(@"RDocumentWinCtrl.insertRdFunctionTemplate bailed; no response from called R session");
rdToolsAreWorking = NO;
return;
}
templateStr = [templateStr stringByReplacingOccurrencesOfString:@"§" withString:@"\n"];
templateStr = [templateStr stringByReplacingOccurrencesOfString:@"mean.POSIXct" withString:NLS(@"FUNCTION_NAME")];
templateStr = [templateStr stringByReplacingOccurrencesOfRegex:@"\\n\\.POSIXct[^\\n]+" withString:@""];
[[myWinCtrl textView] insertText:templateStr];
NSRange newFunRange = [templateStr rangeOfString:NLS(@"FUNCTION_NAME")];
[[myWinCtrl textView] setSelectedRange:newFunRange];
[[myWinCtrl textView] scrollRangeToVisible:newFunRange];
rdToolsAreWorking = NO;
}
- (BOOL) convertRd2PDF
{
if(rdToolsAreWorking) return NO;
rdToolsAreWorking = YES;
BOOL success = YES;
NSError *bashError = nil;
// Try to find the path to the default tex distribution
NSString *texPath = @"";
[myWinCtrl setStatusLineText:[NSString stringWithFormat:@"%@", NLS(@"press ⌘. to cancel")]];
NSString *aPath = [@"which tex" evaluateAsBashCommand];
[myWinCtrl setStatusLineText:@""];
if(aPath && [aPath length]) {
;
} else {
[myWinCtrl setStatusLineText:[NSString stringWithFormat:@"%@", NLS(@"press ⌘. to cancel")]];
aPath = [@"eval `/usr/libexec/path_helper -s` && dirname `which tex`" evaluateAsBashCommand];
[myWinCtrl setStatusLineText:@""];
if(aPath && [aPath length]) {
texPath = [NSString stringWithFormat:@"export PATH=$PATH:%@", aPath];
}
}
NSString *tempName = [NSTemporaryDirectory() stringByAppendingPathComponent: [NSString stringWithFormat: @"%.0f.", [NSDate timeIntervalSinceReferenceDate] * 1000.0]];
NSError *error;
NSString *inputFile = [NSString stringWithFormat: @"%@%@", tempName, @"rd"];
NSString *pdfOutputFile = [NSString stringWithFormat: @"%@%@", tempName, @"pdf"];
NSString *errOutputFile = [NSString stringWithFormat: @"%@%@", tempName, @"txt"];
NSURL *pdfOutputFileURL = [NSURL URLWithString:pdfOutputFile];
[[[myWinCtrl textView] string] writeToFile:inputFile atomically:YES encoding:NSUTF8StringEncoding error:&error];
if(![self checkRdDocumentWithFilePath:inputFile reportSuccess:NO]) {
[[NSFileManager defaultManager] removeItemAtPath:inputFile error:NULL];
[[NSFileManager defaultManager] removeItemAtPath:pdfOutputFile error:NULL];
[myWinCtrl setStatusLineText:@""];
rdToolsAreWorking = NO;
return NO;
}
NSString *convCmd = [NSString stringWithFormat:@"#!/bin/sh\n%@\nR CMD Rd2pdf --no-preview --title='%@' --force --output='%@' '%@' 2>'%@'", texPath, [self displayName], pdfOutputFile, inputFile, errOutputFile];
bashError = nil;
[myWinCtrl setStatusLineText:[NSString stringWithFormat:@"%@ (%@)", NLS(@"Rd → PDF…"), NLS(@"press ⌘. to cancel")]];
[convCmd runAsBashCommandAndError:&bashError];
[myWinCtrl setStatusLineText:@""];
NSFileManager *man = [NSFileManager defaultManager];
if(bashError == nil) {
if([man fileExistsAtPath:pdfOutputFile])
[[HelpManager sharedController] showHelpFileForURL:pdfOutputFileURL];
} else {
NSString *errMessage = [[bashError userInfo] objectForKey:NSLocalizedDescriptionKey];
if([man fileExistsAtPath:errOutputFile]) {
bashError = nil;
NSString *errMessages = [[[NSString alloc]
initWithContentsOfFile:errOutputFile
encoding:NSUTF8StringEncoding
error:&bashError] autorelease];
if(bashError == nil && errMessages && [errMessages length])
errMessage = [errMessage stringByAppendingString:errMessages];
}
NSAlert *alert = [NSAlert alertWithMessageText:NLS(@"Error")
defaultButton:NLS(@"OK")
alternateButton:nil
otherButton:nil
informativeTextWithFormat:[errMessage stringByReplacingOccurrencesOfString:inputFile withString:NLS(@"Rd file")]];
[alert setAlertStyle:NSWarningAlertStyle];
[alert runModal];
[[myWinCtrl window] makeKeyAndOrderFront:self];
[[myWinCtrl window] makeFirstResponder:[myWinCtrl textView]];
[[NSFileManager defaultManager] removeItemAtPath:inputFile error:NULL];
[[NSFileManager defaultManager] removeItemAtPath:pdfOutputFile error:NULL];
[[NSFileManager defaultManager] removeItemAtPath:errOutputFile error:NULL];
rdToolsAreWorking = NO;
return NO;
}
rdToolsAreWorking = NO;
// After 100 secs all temporary files will be deleted even if R was quitted meanwhile
[self performSelector:@selector(removeFiles:) withObject:[NSArray arrayWithObjects:inputFile, pdfOutputFile, errOutputFile, nil] afterDelay:100];
return success;
}
- (BOOL) convertRd2HTML
{
if(rdToolsAreWorking) return NO;
rdToolsAreWorking = YES;
BOOL success = YES;
NSString *tempName = [NSTemporaryDirectory() stringByAppendingPathComponent: [NSString stringWithFormat: @"%.0f.", [NSDate timeIntervalSinceReferenceDate] * 1000.0]];
NSString *RhomeCSS = @"R.css";
NSString *Rhome = [[RController sharedController] home];
if(!Rhome || ![Rhome length]) {
[myWinCtrl setStatusLineText:[NSString stringWithFormat:@"%@", NLS(@"press ⌘. to cancel")]];
Rhome = [@"R --slave --vanilla -e 'cat(R.home())'" evaluateAsBashCommand];
[myWinCtrl setStatusLineText:@""];
}
if(Rhome && [Rhome length]) {
RhomeCSS = [NSString stringWithFormat:@"file://%@/doc/html/R.css", Rhome];
}
NSError *error;
NSString *inputFile = [NSString stringWithFormat: @"%@%@", tempName, @"rd"];
NSString *htmlOutputFile = [NSString stringWithFormat: @"%@%@", tempName, @"html"];
NSURL *htmlOutputFileURL = [NSURL URLWithString:htmlOutputFile];
[[[myWinCtrl textView] string] writeToFile:inputFile atomically:YES encoding:NSUTF8StringEncoding error:&error];
if(![self checkRdDocumentWithFilePath:inputFile reportSuccess:NO]) {
[[NSFileManager defaultManager] removeItemAtPath:inputFile error:NULL];
rdToolsAreWorking = NO;
return NO;
}
error = nil;
[myWinCtrl setStatusLineText:[NSString stringWithFormat:@"%@ (%@)", NLS(@"Rd → HTML…"), NLS(@"press ⌘. to cancel")]];
NSString *convCmd = [NSString stringWithFormat:@"R CMD Rdconv -t html '%@' 2>/dev/null | perl -pe 's!R.css!%@!'> '%@'", inputFile, RhomeCSS, htmlOutputFile];
[convCmd evaluateAsBashCommandAndError:&error];
[myWinCtrl setStatusLineText:@""];
// Try to check if htmlOutputFile has content; if not don't come up with an empty window
BOOL fsizeChecked = NO;
#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
UInt32 fsize = 0;
NSFileManager *man = [[NSFileManager alloc] init];
NSDictionary *attrs = [man attributesOfItemAtPath:htmlOutputFile error:nil];
if(attrs) {
fsize = [attrs fileSize];
fsizeChecked = YES;
}
[man release];
#endif
if(!fsizeChecked || (fsizeChecked && fsize > 0)) {
if(error == nil && [[NSFileManager defaultManager] fileExistsAtPath:htmlOutputFile])
[[HelpManager sharedController] showHelpFileForURL:htmlOutputFileURL];
else {
NSBeep();
success = NO;
}
}
rdToolsAreWorking = NO;
// After 100 secs all temporary files will be deleted even if R was quitted meanwhile
[self performSelector:@selector(removeFiles:) withObject:[NSArray arrayWithObjects:inputFile, htmlOutputFile, nil] afterDelay:100];
return success;
}
- (void)sheetDidEnd:(id)sheet returnCode:(int)returnCode contextInfo:(NSString*)contextInfo
{
// Order out the sheet - could be a NSPanel or NSWindow
if ([sheet respondsToSelector:@selector(orderOut:)]) {
[sheet orderOut:nil];
}
else if ([sheet respondsToSelector:@selector(window)]) {
[[sheet window] orderOut:nil];
}
// Set the input focus to the last doc after closing a sheet
[[(RDocumentController*)[NSDocumentController sharedDocumentController] findLastWindowForDocType:ftRSource] makeKeyAndOrderFront:nil];
}
- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
{
NSString *iid = [toolbarItem itemIdentifier];
if ([iid isEqualToString: RETI_Save ] || [iid isEqualToString: RDETI_Save ])
return [self isDocumentEdited];
return YES;
}
- (void) removeFiles:(NSArray*)files
{
if(files && [files count]) {
NSInteger i = 0;
for(i=0; i<[files count]; i++)
[[NSFileManager defaultManager] removeItemAtPath:[files objectAtIndex:i] error:NULL];
}
}
@end