forked from jmil/SkeinFox
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Controller.m
1109 lines (737 loc) · 43.8 KB
/
Controller.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
//
// Copyright 2009 Jordan Miller, Hive76. All rights reserved.
//
//Jordan Says:
/*
This project and websites were from:
http://forums.macrumors.com/showthread.php?t=420530
http://www.cocoabuilder.com/archive/message/cocoa/2006/5/31/164724
http://att.macrumors.com/attachment.php?attachmentid=99500&d=1201413221
*/
#import "Controller.h"
#import "gitBranch.h"
#import "ShellTask.h"
#import "TableView.h"
#import "gitDateToHumanReadableTransformer.h"
@implementation Controller
@synthesize thisWindow;
@synthesize gitVersion;
@synthesize gitBranches, myArrayController;
@synthesize stlFileToGCode;
@synthesize myTextFieldCell;
@synthesize currentBranch;
@synthesize myTableView;
@synthesize gCodeTaskInBackground;
- (id)init {
self = [super init];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector( readPipe: )
name:NSFileHandleReadCompletionNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(completedTask:)
name:NSTaskDidTerminateNotification
object:nil];
// Define gCodeTaskInBackground here!!
// self.gCodeTaskInBackground = [[[NSTask alloc] init] autorelease];
// [self.gCodeTaskInBackground setLaunchPath: @"/bin/sh"]; //we are launching sh, it is wha will process command for us
// [self.gCodeTaskInBackground setStandardInput:[NSFileHandle fileHandleWithNullDevice]]; //stdin is directed to /dev/null
//
// //we pipe stdout and stderr into a file handle that we read to
// NSPipe *outputPipe = [NSPipe pipe];
// [self.gCodeTaskInBackground setStandardOutput: outputPipe];
// [self.gCodeTaskInBackground setStandardError: outputPipe];
// NSFileHandle *outputFileHandle = [outputPipe fileHandleForReading];
//
//
// // We need to read in background and notify!!!!!
// [outputFileHandle readInBackgroundAndNotify];
//[self.myTextFieldCell setWantsNotificationForMarkedText:NO];
//Set the self.currentBranch default value to 'basic--Raft'
self.currentBranch = [[NSMutableString alloc] initWithString:@"basic--Raft"];
// Register the gitDateToHumanReadableTransformer
/*Based on Apple Demo:
FahrenheitToCelsiusTransformer *fToCTransformer;
// create an autoreleased instance of our value transformer
fToCTransformer = [[[FahrenheitToCelsiusTransformer alloc] init]
autorelease];
// register it with the name that we refer to it with
[NSValueTransformer setValueTransformer:fToCTransformer
forName:@"FahrenheitToCelsiusTransformer"];
*/
gitDateToHumanReadableTransformer *gitDateHumanReadableTransformer;
// create an autoreleased instance of our value transformer
gitDateHumanReadableTransformer = [[[gitDateToHumanReadableTransformer alloc] init] autorelease];
// register it with the name that we refer to it with
[NSValueTransformer setValueTransformer:gitDateHumanReadableTransformer
forName:@"gitDateToHumanReadableTransformer"];
return self;
}
-(void)populateGitBranchesAndSelectCurrentBranch {
// Populate NSTableView with Git branches for .skeinforge directory!
/* Output of:
git branch
* basic--Raft
basic--noRaft
emptyFill-Walt--Raft
emptyFill-Walt--noRaft
watertight--Raft
watertight--noRaft
*/
/* Output of:
git log --branches --no-walk --format='%d %ai'
(watertight--noRaft) 2009-10-15 14:18:56 -0400
(watertight--Raft) 2009-10-15 14:18:10 -0400
(emptyFill-Walt--noRaft) 2009-10-15 14:17:20 -0400
(basic--noRaft) 2009-10-15 14:16:03 -0400
(basic--Raft) 2009-10-15 14:15:07 -0400
(emptyFill-Walt--Raft) 2009-10-15 14:12:25 -0400
*/
NSString *branchesRaw = [ShellTask executeShellCommandSynchronously:@"cd ~/.skeinforge;PATH=/usr/local/bin:/usr/local/git/bin:/opt/local/bin:/sw/bin:$PATH git branch"];
//NSLog(branchesRaw);
NSString *lastModifiedRaw = [ShellTask executeShellCommandSynchronously:@"cd ~/.skeinforge;PATH=/usr/local/bin:/usr/local/git/bin:/opt/local/bin:/sw/bin:$PATH git log --branches --no-walk --format='%d %ai'"];
//NSLog(lastModifiedRaw);
NSArray *namesTemp = [branchesRaw componentsSeparatedByString:@"\n"];
NSMutableArray *names = [NSMutableArray arrayWithArray:namesTemp];
NSArray *lastModifiedTemp = [lastModifiedRaw componentsSeparatedByString:@"\n"];
NSMutableArray *lastModifieds = [NSMutableArray arrayWithArray:lastModifiedTemp];
// Step through array to get dictionary of lastModified Dates
NSInteger lastModifiedIndex = 0;
NSMutableDictionary *lastModifiedDictionary = [[NSMutableDictionary alloc] init];
// We could use regex here, but regex searching is very processor intensive
// Instead we let git do the heavy lifting, so we know the format will be exactly (BRANCH_NAME) DATE based on our git statement above:
// git log --branches --no-walk --format='%d %ai
for (NSString *anElement in lastModifieds) {
if (0 != [anElement length]) {
// Don't try to use substringWithRange on an empty string! you'll get an exception!!
//NSLog(@"'%@' is element %i in this array", anElement, lastModifiedIndex);
// First remove the first two characters
// Try just removing the first two characters. These characters MUST be " (" based on git-log for git 1.6.5 intel leopard
// NSString *openParenChopped = [anElement substringFromIndex:2];
// NSLog(@"'%@' is element %i", openParenChopped, lastModifiedIndex);
// First find the location of Open Parentheses
NSRange openParenLocation = [anElement rangeOfString:@"("];
//NSLog(@"the Range for openParenLocation is: '%i' of length '%i'", openParenLocation.location, openParenLocation.length);
//NSUInteger openParen = openParenLocation.location;
// Next find the location of closed Parentheses
NSRange closeParenLocation = [anElement rangeOfString:@")"];
//NSLog(@"the Range for openParenLocation is: '%i' of length '%i'", closeParenLocation.location, closeParenLocation.length);
// Then the branch name will be the characters between these
NSUInteger startOfBranchName = openParenLocation.location + 1;
NSUInteger branchNameLength = closeParenLocation.location - openParenLocation.location - 1;
NSRange branchNameRange = NSMakeRange(startOfBranchName, branchNameLength);
NSString *thisBranchName = [anElement substringWithRange:branchNameRange];
//NSLog(@"branch name must therefore be '%@'", thisBranchName);
// And then the date last modified will be the characters after closed parentheses + 1 (because we have a ' ' space character in the git log format string
// USE EXACT STRING LENGTH SO THAT WE CAN ADD MORE INFO LATER LIKE CUSTOM NAME FOR THIS BRANCH IN THE COMMIT MESSAGE THAT CAN USE SPECIAL CHARACTERS
// This means the date must be 25 more characters starting at closeParenLocation +2
NSRange lastModifiedDateRange = NSMakeRange((closeParenLocation.location + 2), 25);
NSString *thisBranchModifiedDate = [anElement substringWithRange:lastModifiedDateRange];
//NSLog(@"branch DATE must therefore be '%@'", thisBranchModifiedDate);
// NOTE: here we need special code. This is because if the user has just duplicated a branch, then the git log --branches --no-walk --format='%d %ai command will produce something like this:
// (untitled2,, untitled, basic--Raft) 2009-10-15 14:15:07 -0400
// Which means that thisBranchName is actually multiple different branches, each of which needs to have it's own entry in the mutabledictionary!
// So the workaround is to test if thisBranchName contains the characters ', ' and then split on these characters into a new array, then iterate through the new array and add each to the dictionary with the IDENTICAL last Modified Date
// Now set these variables as the key and value of a new dictionary. Then when we later set the current branch based on the "*" being an early character we will use the branch name as the key to this dictionary to pull out the lastModified date!
// Note, we can do this very simply thanks to the behavior of componentsSeparatedByString:. See here:
/*
NSString *list = @"Norman, Stanley, Fletcher";
NSArray *listItems = [list componentsSeparatedByString:@", "];
produces an array { @"Norman", @"Stanley", @"Fletcher" }.
If list begins with a comma and space—for example, ", Norman, Stanley, Fletcher"—the array has these contents: { @"", @"Norman", @"Stanley", @"Fletcher" }
If list has no separators—for example, "Norman"—the array contains the string itself, in this case { @"Norman" }.
*/
NSArray *allBranchesWithThisDate = [thisBranchName componentsSeparatedByString:@", "];
for (NSString *aBranch in allBranchesWithThisDate) {
//NSLog(@"aBranch is '%@' of type '%@'", aBranch, aBranch.className);
[lastModifiedDictionary setObject:thisBranchModifiedDate forKey:aBranch];
}
lastModifiedIndex++;
}
}
//NSLog(@"My branches with paired last Modified Dates is: '%@'", lastModifiedDictionary);
// Cleanup the Array to both mark the currently selected branch and also to remove leading and lagging whitespace
NSInteger index = 0;
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
for (NSString *element in names) {
// Remove last return character! -- remove lagging whitespace == last newline
if (index != ([names count] - 1)) {
// Check whether 2nd character is *, therefore this is the current branch
if ([[element substringToIndex:1] isEqualToString: @"*"] ) {
[[self currentBranch] setString:[element substringFromIndex:2]];
//NSLog(@"I am the current branch, and my name is '%@' @index '%i'", [element substringFromIndex:2], index);
}
// Remove first 3 characters before adding to the tempArray
[tempArray addObject:[element substringFromIndex:2]];
}
index++;
}
[names setArray:tempArray];
[tempArray release];
//NSArray *names = [NSArray arrayWithObjects:@"Bird", @"Chair", @"Song", @"Computer", nil];
NSMutableArray *tempGitBranches = [NSMutableArray array];
for (NSString *name in names) {
gitBranch *branch = [[[gitBranch alloc] init] autorelease];
branch.name = name;
//branch.lastModified = @"last modified on XXXXX";
branch.lastModified = [lastModifiedDictionary objectForKey:name];
[tempGitBranches addObject:branch];
}
// Since we use Cocoa Bindings, AS SOON AS self.gitBranches is defined, the table will be as well!
self.gitBranches = tempGitBranches;
// Now that the table is populated, we must immediately tell the table which row to select!
for (gitBranch *thisBranch in self.gitBranches) {
//NSLog(@"my branch name is:%@", whoami.name);
if ([thisBranch.name isEqualToString:self.currentBranch]) {
//NSLog(@"Yes!! the currentBranch '%@' is verified as identical to '%@'!!!", self.currentBranch, thisBranch.name);
[myArrayController setSelectedObjects:[NSArray arrayWithObjects:thisBranch, nil]];
}
}
//NSLog(@"myArrayController selection index is currently %i", [myArrayController selectionIndex]);
// We also DON'T need to update the GitBranchSelection since we have just selected the current Branch!!!
//[self didUpdateGitBranchSelection:self];
// [self.myTableView reloadData];
// [self.myTableView setNeedsDisplay:YES];
// Release lastModifiedDictionary!!
[lastModifiedDictionary release];
}
- (IBAction)addGitBranch:(id)sender {
NSString *prefix = @"cd ~/.skeinforge;PATH=/usr/local/bin:/usr/local/git/bin:/opt/local/bin:/sw/bin:$PATH git checkout -f -b ";
NSString *commandToExecute = [prefix stringByAppendingString:@"untitled"];
NSString *newBranchName;
newBranchName = [self.currentBranch stringByAppendingString:@"-copy"];
//NSLog(newBranchName);
//NSString *commandToExecute = [prefix stringByAppendingString:newBranchName];
//NSLog(commandToExecute);
// Perform the shelltask and print it immediately to the console
[self executeStringCommandSynchronouslyAndLogToConsole:commandToExecute isAShellTask:YES];
[self populateGitBranchesAndSelectCurrentBranch];
[self didRenameGitBranch:newBranchName];
//NSLog(@"addedGitBranch!");
}
- (IBAction)delGitBranch:(id)sender {
NSAlert *alert = [[NSAlert alloc] init];
[alert addButtonWithTitle:@"Cancel"];
[alert addButtonWithTitle:@"OK"];
[alert setMessageText:@"Delete the selected settings template?"];
[alert setInformativeText:@"Deleted settings templates cannot be restored."];
[alert setAlertStyle:NSWarningAlertStyle];
if ([alert runModal] == NSAlertSecondButtonReturn) {
// OK clicked, delete the record
// To delete it's a bit more complicated because we CANNOT delete the branch that we have currently checked out; So we should figure out which branch we have currently selected and store that name temporarily, then select the branch below it (or the branch above it if it is the last branch), then delete the branch above it and reload the gitbranches
[self.currentBranch setString:[[[myArrayController selectedObjects] objectAtIndex:0] name]];
//NSLog(@"the branch to delete is: %@", self.currentBranch);
NSUInteger currentSelectionIndexToDelete = self.myArrayController.selectionIndex;
NSUInteger nextSelectionIndex = 0;
//NSLog(@"the branchIndex to delete is: %i", currentSelectionIndexToDelete);
NSString *branchToDelete = [[[myArrayController selectedObjects] objectAtIndex:0] name];
// Select the next or previous row as possible given how many objects are in the myArrayController
// NOTE: cannot use selectNext: and selectPrevious: because:
// "Beginning with Mac OS X v10.4 the result of this method is deferred until the next iteration of the runloop so that the error presentation mechanism can provide feedback as a sheet."
if (self.myArrayController.canSelectNext) {
// set the array controller selection to the next one
//[self.myArrayController selectNext:self];
nextSelectionIndex = currentSelectionIndexToDelete + 1;
} else if (self.myArrayController.canSelectPrevious) {
// set the array controller selection to the previous one
//[self.myArrayController selectPrevious:self];
nextSelectionIndex = currentSelectionIndexToDelete - 1;
}
// // Make Sure we actually change branches!!
[myArrayController setSelectionIndex:nextSelectionIndex];
[self didUpdateGitBranchSelection:self];
//[self.myTableView reloadData];
//NSLog(@"currentIndexToDelete %i, nextSelectionIndex %i", currentSelectionIndexToDelete, nextSelectionIndex);
// NSLog(@"branchToDelete is %@, while the newly selected branch is now %@", branchToDelete, [[[myArrayController selectedObjects] objectAtIndex:0] name]);
NSString *prefix = @"cd ~/.skeinforge;PATH=/usr/local/bin:/usr/local/git/bin:/opt/local/bin:/sw/bin:$PATH git branch -D ";
NSString *commandToExecute = [prefix stringByAppendingString:branchToDelete];
//
// Perform the shelltask and print it immediately to the console
[self executeStringCommandSynchronouslyAndLogToConsole:commandToExecute isAShellTask:YES];
//NSLog(@"%@ was deleted", branchToDelete);
// Make sure table view reloads appropriately!!
[self populateGitBranchesAndSelectCurrentBranch];
//[self.gitBranches removeAllObjects];
}
[alert release];
}
- (void)completedTask:(NSNotification *)aNotification {
// NSLog(@"'%@' ", aNotification.name);
//
// NSLog(@"the termination reason is %i", [gCodeTaskInBackground terminationStatus]);
[gCodeMeButton setTitle:@"Create GCode"];
//Reenable the gCodeMe button since we still have an .stl file selected...
// On launch, a task is run for some reason, so we need to check if there is an .stl file loaded. If so, then keep gcodeMeButton enabled!
if ([self.stlFileToGCode isNotEqualTo:nil]) {
[gCodeMeButton setEnabled:YES];
}
[launchButton setEnabled:YES];
[gitCommitButton setEnabled:YES];
[addGitBranchButton setEnabled:YES];
[delGitBranchButton setEnabled:YES];
[myTableView setEnabled:YES];
[indicator stopAnimation:nil];
}
- (void)readPipe:(NSNotification *)aNotification {
// See http://macosx.com/forums/software-programming-web-scripting/4522-better-way-read-nstask.html
//NSLog(@"We are reading live output from standard output as it is being written, because we are being notified each time it's being written!!!");
NSData *data;
NSString *text;
// if( [notification object] != _fileHandle )
// return;
//NSLog(@"the userinfo NSDictionary is \n %@", [aNotification userInfo]);
data = [[aNotification userInfo]
objectForKey:NSFileHandleNotificationDataItem];
text = [[NSString alloc] initWithData:data
encoding:NSASCIIStringEncoding];
// Do something with your text
// ...
NSAttributedString *string = [[NSAttributedString alloc] initWithString:text];
NSTextStorage *storage = [progressLogConsoleTextView textStorage];
[storage beginEditing];
[storage appendAttributedString:string];
[storage endEditing];
[string release];
[self scrollToBottom:self];
//NSLog(text);
[text release];
//NSLog(@"the data are '%@'", data);
// If the task is still running, then keep reading!!
if ([data length] != 0) {
[[aNotification object] readInBackgroundAndNotify];
}
// if ([data length] == 0) {
// NSLog(@"MY DATA ARE NIL!!!!!!!");
// }
}
- (void)awakeFromNib {
// Check if git is installed!
NSString *gitVersionRaw = [ShellTask executeShellCommandSynchronously:@"PATH=/usr/local/bin:/usr/local/git/bin:/opt/local/bin:/sw/bin:$PATH git --version"];
// if ([gitVersionRaw ]) {
//
// }
//
// [];
//
//NSLog(@"The raw git version is '%@'", gitVersionRaw);
NSArray *gitVersionArray = [gitVersionRaw componentsSeparatedByString:@"\n"];
NSString *gitVersionSingleLine = [gitVersionArray objectAtIndex:0];
//NSLog(@"The single line git version is '%@'", gitVersionSingleLine);
NSString *gitVersionDotNumberRaw = [gitVersionSingleLine substringFromIndex:12];
NSLog(@"Git version '%@' detected", gitVersionDotNumberRaw);
NSArray *gitVersionArrayNoDots = [gitVersionDotNumberRaw componentsSeparatedByString:@"."];
//NSLog(@"%@", gitVersionArrayNoDots);
// Now the git version number may not contain 4 numbers like '1.6.4.2', and may instead contain '1.7'. So, we need to compare each number successively!
NSArray *gitVersionRequired = [NSArray arrayWithObjects:@"1", @"6", @"4", nil];
if ([gitVersionArrayNoDots count] >= 1) {
NSString *gVno1 = [gitVersionArrayNoDots objectAtIndex:0];
//NSLog(@"%@", gVno1);
if ([gVno1 intValue] >= [[gitVersionRequired objectAtIndex:0] intValue]) {
//NSLog(@"we are at least at version %@", [gitVersionRequired objectAtIndex:0]);
// so we are at least at version 1
if ([gitVersionArrayNoDots count] >= 2) {
NSString *gVno2 = [gitVersionArrayNoDots objectAtIndex:1];
//NSLog(@"%@", gVno2);
if ([gVno2 intValue] >= [[gitVersionRequired objectAtIndex:1] intValue]) {
//NSLog(@"we are at least at version %@", [gitVersionRequired objectAtIndex:1]);
if ([gitVersionArrayNoDots count] >= 3) {
NSString *gVno3 = [gitVersionArrayNoDots objectAtIndex:2];
//NSLog(@"%@", gVno3);
if ([gVno3 intValue] >= [[gitVersionRequired objectAtIndex:2] intValue]) {
//NSLog(@"we are at least at version %@", [gitVersionRequired objectAtIndex:2]);
} else {
[self notifyUserImproperGitVersion:gitVersionDotNumberRaw gitVersionRequiredArray:gitVersionRequired];
}
}
} else {
[self notifyUserImproperGitVersion:gitVersionDotNumberRaw gitVersionRequiredArray:gitVersionRequired];
}
}
} else {
[self notifyUserImproperGitVersion:gitVersionDotNumberRaw gitVersionRequiredArray:gitVersionRequired];
}
}
// NSString *gVno2 = [gitVersionArrayNoDots objectAtIndex:1];
// NSString *gVno3 = [gitVersionArrayNoDots objectAtIndex:2];
// NSString *gVno4 = [gitVersionArrayNoDots objectAtIndex:3];
// NSString *gVno5 = [gitVersionArrayNoDots objectAtIndex:4];
// NSLog(@"%@ %@ %@ %@ %@", gVno1, gVno2, gVno3, gVno4, gVno5);
// Actually have to remove the trailing return in the array!
// NSString *gVnoDots = [[[gitVersionArrayNoDots componentsJoinedByString:@""] componentsSeparatedByString:@"/n"] objectAtIndex:0];
//
// NSLog(@"The git version is '%@'", gVnoDots);
// Display the version number in the app window
[self setConcatenatedWindowTitle];
// See if .skeinforge Directory exists
NSString *skeinforgeConfigDirectory = [@"~/.skeinforge" stringByExpandingTildeInPath];
//NSLog(skeinforgeConfigDirectory);
NSString *skeinforgeMasterTemplatesDirectory = [[NSBundle mainBundle] pathForResource:@".skeinforge" ofType:nil];
//NSLog(@"The .skeinforge master template folder is located at: '%@'", skeinforgeMasterTemplatesDirectory);
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL fileExists = [fileManager fileExistsAtPath:skeinforgeConfigDirectory];
if (!fileExists) {
//NSLog(@".skeinforge directory DOES NOT exist!");
// If .skeinforge doesn't exist, then copy it from the current application resources
if ([fileManager copyItemAtPath:skeinforgeMasterTemplatesDirectory toPath:skeinforgeConfigDirectory error:nil]) {
NSLog(@"Skeinforge Directory copy SUCCESS");
} else {
NSLog(@"Skeinforge Directory copy FAILURE");
}
} else {
//NSLog(@".skeinforge directory exists!");
// If the .git directory doesn't already exist... if it already exists, DON'T OVERWRITE IT. People will be pissed!
NSString *gitConfigDirectory = [skeinforgeConfigDirectory stringByAppendingString:@"/.git"];
//NSLog(gitConfigDirectory);
BOOL gitExists = [fileManager fileExistsAtPath:gitConfigDirectory];
if (!gitExists) {
// If .skeinforge directory already exists, and the .git DOES NOT exist, then we should just initiate a brand new .git repo and DO NOT TRY TO COPY OR INTERLEAVE GIT BRANCHES with that of the current user
NSString *prefix = @"cd ~/.skeinforge;PATH=/usr/local/bin:/usr/local/git/bin:/opt/local/bin:/sw/bin:$PATH git init; PATH=/usr/local/bin:/usr/local/git/bin:/opt/local/bin:/sw/bin:$PATH git add .; PATH=/usr/local/bin:/usr/local/git/bin:/opt/local/bin:/sw/bin:$PATH git commit -a -m 'hello'; PATH=/usr/local/bin:/usr/local/git/bin:/opt/local/bin:/sw/bin:$PATH git branch -M ";
NSString *commandToExecute = [prefix stringByAppendingString:NSUserName()];
//NSLog(commandToExecute);
// Perform the shelltask and print it immediately to the console
[self executeStringCommandSynchronouslyAndLogToConsole:commandToExecute isAShellTask:YES];
} else {
//NSLog(@"%@'s .git directory exists, so don't mess with it", NSUserName());
// So we do nothing
}
}
// Now we definitely have a .skeinforge directory with a .git repo inside of it
// So setup all of our table variables
[self populateGitBranchesAndSelectCurrentBranch];
NSString *logMessage = [NSString stringWithFormat:@"'%@' is the current branch\n", self.currentBranch];
[self executeStringCommandSynchronouslyAndLogToConsole:logMessage isAShellTask:NO];
//*******************
// Control for Interface Elements setup
//*******************
// Turn off interface buttons!
//[popUpButton setEnabled:NO];
[gCodeMeButton setTitle:@"Create GCode"];
[gCodeMeButton setEnabled:NO];
[launchButton setEnabled:YES];
[consoleToggleMenuItem setTitle:@"Show Console"];
[consoleToggleButton setState:NSOffState];
[stlFileNameDisplay setStringValue:@""];
// Register for Dragtypes so that we can accept drag-and-dropped .stl files!
// NSArray *dragTypes = [NSArray arrayWithObjects:<#(id)firstObj#>];
// [self.window registerForDraggedTypes:[NSArray arrayWithObjects:NSColorPboardType,NSFilenamesPboardType, nil]];
NSArray *dragTypes = [NSArray arrayWithObjects:NSFilenamesPboardType, nil];
[window registerForDraggedTypes:dragTypes];
[self setupBundleNameInMenuBar];
}
- (void) notifyUserImproperGitVersion:(NSString *)gitVersionDotNumberRaw gitVersionRequiredArray:(NSArray *)gitVersionRequired {
NSString *alertMessage = [NSString stringWithFormat:@"You are at git version '%@' while git version '%@' or later is required.", gitVersionDotNumberRaw, [gitVersionRequired componentsJoinedByString:@"."]];
NSLog(@"%@", alertMessage);
NSAlert *alert = [[NSAlert alloc] init];
[alert addButtonWithTitle:@"OK"];
//[alert addButtonWithTitle:@"Cancel"];
[alert setMessageText:alertMessage];
[alert setInformativeText:@"Please update to a later version of git."];
[alert setAlertStyle:NSWarningAlertStyle];
if ([alert runModal] == NSAlertFirstButtonReturn) {
// OK clicked, QUIT THE APPLICATION
[NSApp terminate:self];
}
[alert release];
}
- (void) executeStringCommandSynchronouslyAndLogToConsole:(NSString *)commandToExecute isAShellTask:(BOOL)isAShellTask {
// Perform the shelltask and print it immediately to the console
NSAttributedString *string;
if (isAShellTask) {
// Execute the command and get the output
string = [[NSAttributedString alloc] initWithString:[ShellTask executeShellCommandSynchronously:commandToExecute]];
} else {
string = [[NSAttributedString alloc] initWithString:commandToExecute];
}
NSTextStorage *storage = [progressLogConsoleTextView textStorage];
[storage beginEditing];
[storage appendAttributedString:string];
[storage endEditing];
[string release];
[self scrollToBottom:self];
}
- (void)setupBundleNameInMenuBar {
NSString *appName = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleNameKey];
if (appName == nil) appName = [[NSProcessInfo processInfo] processName];
NSMenu *menuBar = [NSApp mainMenu];
for (NSMenuItem *menuItem in [menuBar itemArray])
[self replaceTitlePlaceholderInMenuItem: menuItem withString: appName];
}
- (void)replaceTitlePlaceholderInMenuItem:(NSMenuItem *)root withString:(NSString *)appName {
root.title = [root.title stringByReplacingOccurrencesOfString: @"NewApplication"
withString: appName];
NSArray *submenuItems = [root.submenu itemArray];
for (NSMenuItem *menuItem in submenuItems)
[self replaceTitlePlaceholderInMenuItem: menuItem withString: appName];
}
- (BOOL)tableView:(NSTableView *)aTableView shouldSelectRow:(NSInteger)rowIndex {
// NSLog(@"tableView:aTableView called!!!");
//
// NSLog(@"TableView Should select row #%i!!!", rowIndex);
// NSLog(@"BUT my current selection index in myArrayController is: %i", [myArrayController selectionIndex]);
//NSLog(@"Which Contains: %@", [myArrayController ]);
// Now setting the selection index for this object!!
[myArrayController setSelectionIndex:rowIndex];
//NSLog(@"NOW my current selection index in myArrayController is: %i", [myArrayController selectionIndex]);
//Switch Git Branches!!!!
[self didUpdateGitBranchSelection:self];
// Since a branch was selected, update the window name with the branch name!
// [self setConcatenatedWindowTitle];
return YES;
}
- (void) setConcatenatedWindowTitle {
NSString *currentVersionNumber = [[NSString stringWithString:@" v"] stringByAppendingString:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]];
//NSLog(@"'%@' is the version number", currentVersionNumber);
NSString *appNameVersion = [[[NSProcessInfo processInfo] processName] stringByAppendingString:currentVersionNumber];
//[self.thisWindow setTitle:[appNameWithColonSpace stringByAppendingString:[[[myArrayController selectedObjects] objectAtIndex:0] name]]];
[self.thisWindow setTitle:appNameVersion];
}
- (void)consoleToggle:(id)sender {
//NSLog(@"Console toggled");
if ([consoleDrawer state] == NSDrawerOpenState) {
// About to close...
[consoleToggleMenuItem setTitle:@"Show Console"];
[consoleToggleButton setState:NSOffState];
} else {
// About to open...
[consoleToggleMenuItem setTitle:@"Hide Console"];
[consoleToggleButton setState:NSOnState];
}
// Perform the toggle
[consoleDrawer toggle:self];
}
- (void)clearConsole:(id)sender {
NSAttributedString *string = [[NSAttributedString alloc] initWithString:@""];
NSTextStorage *storage = [progressLogConsoleTextView textStorage];
[storage beginEditing];
[storage setAttributedString:string];
[storage endEditing];
[string release];
[self scrollToBottom:self];
}
- (void)processFile {
[popUpButton setEnabled:NO];
[launchButton setEnabled:NO];
[launchButton setEnabled:NO];
[gitCommitButton setEnabled:NO];
[addGitBranchButton setEnabled:NO];
[delGitBranchButton setEnabled:NO];
[myTableView setEnabled:NO];
// Disable gCodeMeButton and start the indicator spinning animation
[gCodeMeButton setEnabled:NO];
[gCodeMeButton setTitle:@"Running..."];
[indicator startAnimation:nil];
//[openFile setEnabled:NO];
}
// Drag and drop .stl files!
- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender {
//NSLog(@"dragging entered and started!!");
NSView *view = [window contentView];
if (![self dragIsFile:sender]) {
return NSDragOperationNone;
}
[view lockFocus];
[[NSColor selectedControlColor] set];
[NSBezierPath setDefaultLineWidth:5];
[NSBezierPath strokeRect:[view bounds]];
[view unlockFocus];
[window flushWindow];
return NSDragOperationGeneric;
}
//- (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender {
// NSLog(@"dragging updated!!");
// return NSDragOperationAll;
//}
- (NSDragOperation)draggingExited:(id <NSDraggingInfo>)sender {
//NSLog(@"dragging exited!!");
// Remove Border Highlighting when dragging exited
[[window contentView] setNeedsDisplay:YES];
return NSDragOperationAll;
}
- (NSDragOperation)prepareForDragOperation:(id <NSDraggingInfo>)sender {
//NSLog(@"preparing for drag operation!!");
// Remove Window View Border Highlighting when dragging released
[[window contentView] setNeedsDisplay:YES];
return NSDragOperationAll;
}
- (NSDragOperation)performDragOperation:(id <NSDraggingInfo>)sender {
//NSLog(@"perform drag operation!!");
NSString *filename = [self getFileForDrag:sender];
//NSLog(@"my filename is '%@'", filename);
self.stlFileToGCode = filename;
[stlFileNameDisplay setStringValue:[self stlFileToGCode]];
[gCodeMeButton setEnabled:YES];
return NSDragOperationAll;
}
- (BOOL)dragIsFile:(id <NSDraggingInfo>)sender
{
BOOL isDirectory;
NSString *dragFilename = [self getFileForDrag:sender];
[[NSFileManager defaultManager] fileExistsAtPath:dragFilename isDirectory:&isDirectory];
//NSLog(@"I am not a directory '%@'", isDirectory);
return !isDirectory;
}
- (NSString *)getFileForDrag:(id <NSDraggingInfo>)sender
{
NSPasteboard *pb = [sender draggingPasteboard];
NSString *availableType = [pb availableTypeFromArray:[NSArray arrayWithObjects:NSFilenamesPboardType, nil]];
NSString *dragFilename;
NSArray *props;
props = [pb propertyListForType:availableType];
dragFilename = [props objectAtIndex:0];
return dragFilename;
}
// Send a notification to self that the user did update the git branch selection
- (IBAction) didUpdateGitBranchSelection:(id)sender {
// NSLog(@"I was selected!!");
// NSLog(@"my current selection index in myArrayController is: %i", [myArrayController selectionIndex]);
// NSLog(@"my current selection objects in myArrayController is: %@", [myArrayController selectedObjects]);
// NSLog(@"my current selection OBJECT NAME IS: %@", [[[myArrayController selectedObjects] objectAtIndex:0] name]);
[self.currentBranch setString:[[[myArrayController selectedObjects] objectAtIndex:0] name]];
NSString *selectedItemName = [[[myArrayController selectedObjects] objectAtIndex:0] name];
// Force Git Checkout; this is what the user will expect, that we will switch branches. any modifications to skeinforge will be thrown away. later we can give another option to not throw away changes and notify user that there were changes and let them fix things...
NSString *prefix = @"cd ~/.skeinforge;PATH=/usr/local/bin:/usr/local/git/bin:/opt/local/bin:/sw/bin:$PATH git checkout -f ";
NSString *commandToExecute = [prefix stringByAppendingString:selectedItemName];
// NSLog(@"'%@'", commandToExecute);
// NSString *checkoutResult = [ShellTask executeShellCommandSynchronously:commandToExecute];
// NSLog(checkoutResult);
[self executeStringCommandSynchronouslyAndLogToConsole:commandToExecute isAShellTask:YES];
}
// Edited the settings in Skeinforge, so now we need to commit the changes
// git add .; git commit -a -m "DateTimeStamp"
- (IBAction) didUpdateGitBranchSettings:(id)sender {
NSString *prefix = @"cd ~/.skeinforge;PATH=/usr/local/bin:/usr/local/git/bin:/opt/local/bin:/sw/bin:$PATH git add .;PATH=/usr/local/bin:/usr/local/git/bin:/opt/local/bin:/sw/bin:$PATH git commit -a -m ";
// Get the current date!!
NSDateFormatter *dateFormatter =
[[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
NSDate *date = [NSDate date];
NSString *formattedDateString = [dateFormatter stringFromDate:date];
//NSLog(@"formattedDateString for locale %@: %@", [[dateFormatter locale] localeIdentifier], formattedDateString);
// Output: formattedDateString for locale en_US: Jan 2, 2001
//NSLog(@"the date/time for the git log message is: '%@'", formattedDateString);
NSString *commandToExecute = [prefix stringByAppendingString:[NSString stringWithFormat:@"\"%@ @ %@\"", NSUserName(), formattedDateString]];
//NSLog(@"'%@'", commandToExecute);
[self executeStringCommandSynchronouslyAndLogToConsole:commandToExecute isAShellTask:YES];
// Update lastModified dates!!!
[self populateGitBranchesAndSelectCurrentBranch];
//NSLog(branchesRaw);
//NSLog(@"Controller didUpdateGitBranchSettings to commit them!!");
}
// We renamed the branch name, so now we need to actually rename the branch name on disk
// Note that changes may be present, BUT DO NOT DO A COMMIT! The user will not expect a rename will also commit any changes present. This is EXPLICITLY and EXCLUSIVELY what the "Save Changes" button is for!
// git branch -M "NewBranchName"
- (IBAction)didRenameGitBranch:(NSString *)newBranchName {
//NSLog(@"Controller didRenameGitBranch");
//NSLog(newBranchName);
// Note that changes may be present, BUT DO NOT DO A COMMIT! The user will not expect a rename will also commit any changes present. This is EXPLICITLY and EXCLUSIVELY what the "Save Changes" button is for!
// First we commit the current branch in case there are any changes
//[self didUpdateGitBranchSettings:self];
NSString *prefix = @"cd ~/.skeinforge;PATH=/usr/local/bin:/usr/local/git/bin:/opt/local/bin:/sw/bin:$PATH git branch -M ";
NSString *commandToExecute = [prefix stringByAppendingString:newBranchName];
//NSLog(@"The New Branch Name will be %@", newBranchName);
//NSLog(@"The Command to Execute will be '%@'", commandToExecute);
// Perform the shelltask and print it immediately to the console
[self executeStringCommandSynchronouslyAndLogToConsole:commandToExecute isAShellTask:YES];
[self populateGitBranchesAndSelectCurrentBranch];
// Don't log the new branch name here, because git does not produce output for renamed branch. Rather, just leave it blank on success
// NSString *logMessage = [NSString stringWithFormat:@"Renamed branch to '%@'", newBranchName];
// [self executeStringCommandSynchronouslyAndLogToConsole:logMessage isAShellTask:NO];
//NSLog(@"renamed git branch!!");
}
- (void)scrollToBottom:(id)sender {
// Scroll to the bottom!!!
// get the current scroll position of the document view
//NSPoint currentScrollPosition=[[progressLogConsoleScrollView contentView] bounds].origin;
NSPoint newScrollOrigin;
// assume that the scrollview is an existing variable
if ([[progressLogConsoleScrollView documentView] isFlipped]) {
// newScrollOrigin=NSMakePoint(0.0,NSMaxY([[progressLogConsoleScrollView documentView] frame]) - NSHeight([[progressLogConsoleScrollView contentView] bounds]));
newScrollOrigin=NSMakePoint(0.0,NSMaxY([[progressLogConsoleScrollView documentView] frame]));
} else {
newScrollOrigin=NSMakePoint(0.0,0.0);
}
[[progressLogConsoleScrollView documentView] scrollPoint:newScrollOrigin];
}
- (IBAction) launchSkeinforge:(id)sender {
//NSLog(@"A request to launch SkeinForge was received");
// Use the Skeinforge that is contained within this application package!!
//NSString *pathToSkeinforge = [[NSBundle mainBundle] pathForResource:@"skeinforge-0005" ofType:nil];
NSString *pathToSkeinforge = [[NSBundle mainBundle] pathForResource:@"skeinforge-0006" ofType:nil];
//NSString *pathToSkeinforge = [[NSBundle mainBundle] pathForResource:@"reprap_python_beanshell" ofType:nil];
//NSLog(@"the path to skeinforge is: '%@'", pathToSkeinforge);
NSString *skeinforgePy = @"/skeinforge.py";