File: PCProjectBuilder.m

package info (click to toggle)
projectcenter.app 0.6.2%2Bgit20190606-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 2,968 kB
  • sloc: objc: 20,132; ansic: 1,463; makefile: 38
file content (1341 lines) | stat: -rw-r--r-- 36,508 bytes parent folder | download | duplicates (3)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
/*
   GNUstep ProjectCenter - http://www.gnustep.org/experience/ProjectCenter.html

   Copyright (C) 2000-2014 Free Software Foundation

   Authors: Philippe C.D. Robert
            Serg Stoyan
	    Riccardo Mottola

   This file is part of GNUstep.

   This application 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 application 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
   Library General Public License for more details.

   You should have received a copy of the GNU General Public
   License along with this library; if not, write to the Free
   Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA.
*/

#import <AppKit/AppKit.h>

#import <ProjectCenter/PCDefines.h>
#import <ProjectCenter/PCButton.h>

#import <ProjectCenter/PCFileManager.h>

#import <ProjectCenter/PCProjectManager.h>
#import <ProjectCenter/PCProject.h>
#import <ProjectCenter/PCProjectWindow.h>
#import <ProjectCenter/PCProjectBuilder.h>
#import <ProjectCenter/PCProjectBuilderOptions.h>

#import <ProjectCenter/PCProjectEditor.h>
#import <Protocols/CodeEditor.h>
#import <ProjectCenter/PCSaveModified.h>

#import <ProjectCenter/PCLogController.h>
#import <Protocols/Preferences.h>

#import "../Modules/Preferences/Build/PCBuildPrefs.h"

#ifndef IMAGE
#define IMAGE(X) [NSImage imageNamed: X]
#endif

#ifndef NOTIFICATION_CENTER
#define NOTIFICATION_CENTER [NSNotificationCenter defaultCenter]
#endif

@implementation PCProjectBuilder

- (id)initWithProject:(PCProject *)aProject
{
#ifdef DEBUG
  NSLog (@"PCProjectBuilder: initWithProject");
#endif

  NSAssert(aProject, @"No project specified!");
  
  if ((self = [super init]))
    {
      project = aProject;
      buildStatusTarget = [[NSMutableString alloc] initWithString:@"all"];
      buildTarget = [[NSMutableString alloc] initWithString:@"all"];
      buildArgs = [[NSMutableArray array] retain];
      buildOptions = [[PCProjectBuilderOptions alloc] initWithProject:project
							     delegate:self];
      postProcess = NULL;
      makeTask = nil;
      _isBuilding = NO;
      _isCleaning = NO;
      _isCVLoaded = NO;

      if ([NSBundle loadNibNamed:@"Builder" owner:self] == NO)
	{
	  PCLogError(self, @"error loading Builder NIB file!");
	  return nil;
	}
      [[NSNotificationCenter defaultCenter]
	addObserver:self
	   selector:@selector(loadPreferences:)
	       name:PCPreferencesDidChangeNotification
	     object:nil];
      [self loadPreferences:nil];
    }

  return self;
}

- (void)dealloc
{
#ifdef DEBUG
  NSLog (@"PCProjectBuilder: dealloc");
#endif

  [[NSNotificationCenter defaultCenter] removeObserver:self];

  if ([componentView superview])
    {
      [componentView removeFromSuperview];
    }

  RELEASE(buildStatusTarget);
  RELEASE(buildTarget);
  RELEASE(buildArgs);
  RELEASE(buildOptions);

  RELEASE(successSound);
  RELEASE(failureSound);
  RELEASE(rootBuildDir);
  RELEASE(buildTool);

//  NSLog(@"Project Builder--> componentView RC: %i", 
//	[componentView retainCount]);

  RELEASE(componentView);
  RELEASE(errorArray);
  RELEASE(errorString);

//  NSLog(@"Project Builder--> RC: %i", [self retainCount]);

  [super dealloc];
}

- (void)awakeFromNib
{
  NSScrollView *errorScroll; 
  NSScrollView *logScroll;

  if (_isCVLoaded)
    {
      return;
    }

//  NSLog(@"ProjectBuilder awakeFromNib");

  [componentView retain];
  [componentView removeFromSuperview];

//  NSLog(@"ProjectBuilder awakeFromNib: componentView RC:%i", 
//	[componentView retainCount]);

  /*
   * 4 build Buttons
   */
  [buildButton setToolTip:@"Build"];
  [buildButton setImage:IMAGE(@"Build")];

  [cleanButton setToolTip:@"Clean"];
  [cleanButton setImage:IMAGE(@"Clean")];

  [optionsButton setToolTip:@"Build Options"];
  [optionsButton setImage:IMAGE(@"Options")];
  
  [errorsCountField setStringValue:@""];
  [self updateTargetField];

  /*
   *  Error output
   */
  errorArray = [[NSMutableArray alloc] initWithCapacity:0];
  errorString = [[NSMutableString alloc] initWithString:@""];

  errorImageColumn = [[NSTableColumn alloc] initWithIdentifier:@"ErrorImage"];
  [errorImageColumn setEditable:NO];
  [errorImageColumn setWidth:20.0];
  errorColumn = [[NSTableColumn alloc] initWithIdentifier:@"Error"];
  [errorColumn setEditable:NO];

  errorOutput = [[NSTableView alloc]
    initWithFrame:NSMakeRect(0,0,209,111)];
  [errorOutput setAllowsMultipleSelection:NO];
  [errorOutput setAllowsColumnReordering:NO];
  [errorOutput setAllowsColumnResizing:NO];
  [errorOutput setAllowsEmptySelection:YES];
  [errorOutput setAllowsColumnSelection:NO];
  [errorOutput setRowHeight:19.0];
  [errorOutput setCornerView:nil];
  [errorOutput setHeaderView:nil];
  [errorOutput addTableColumn:errorImageColumn];
  [errorOutput addTableColumn:errorColumn];
  [errorOutput setDataSource:self];
  [errorOutput setBackgroundColor:[NSColor colorWithDeviceRed:0.88
			                                green:0.76 
			                                 blue:0.60 
			                                alpha:1.0]];
  [errorOutput setDrawsGrid:NO];
  [errorOutput setTarget:self];
  [errorOutput setAction:@selector(errorItemClick:)];

  errorScroll = [[NSScrollView alloc] initWithFrame:NSMakeRect(0,0,464,120)];
  [errorScroll setHasHorizontalScroller:NO];
  [errorScroll setHasVerticalScroller:YES];
  [errorScroll setBorderType:NSBezelBorder];
  [errorScroll setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];

  [errorScroll setDocumentView:errorOutput];
  RELEASE(errorOutput);

  /*
   *  Log output
   */
  logScroll = [[NSScrollView alloc] initWithFrame:NSMakeRect(0,0,480,133)];
  [logScroll setHasHorizontalScroller:NO];
  [logScroll setHasVerticalScroller:YES];
  [logScroll setBorderType:NSBezelBorder];
  [logScroll setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];

  logOutput = [[NSTextView alloc] 
    initWithFrame:[[logScroll contentView] frame]];
  [logOutput setRichText:NO];
  [logOutput setEditable:NO];
  [logOutput setSelectable:YES];
  [logOutput setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
  [logOutput setBackgroundColor:[NSColor lightGrayColor]];
  [[logOutput textContainer] setWidthTracksTextView:YES];
  [[logOutput textContainer] setHeightTracksTextView:YES];
  [logOutput setHorizontallyResizable:NO];
  [logOutput setVerticallyResizable:YES];
  [logOutput setMinSize:NSMakeSize(0, 0)];
  [logOutput setMaxSize:NSMakeSize(1E7, 1E7)];
  [[logOutput textContainer] setContainerSize: 
    NSMakeSize ([logOutput frame].size.width, 1e7)];
  [[logOutput textContainer] setWidthTracksTextView:YES];

  [logScroll setDocumentView:logOutput];
  RELEASE(logOutput);

  /*
   * Split view
   */
  [split addSubview:errorScroll];
  RELEASE(errorScroll);
  [split addSubview:logScroll];
  RELEASE(logScroll);

//  [split adjustSubviews];
//  [componentView addSubview:split];
//  RELEASE (split);

  _isCVLoaded = YES;
}

- (NSView *)componentView
{
  return componentView;
}

- (void)loadPreferences:(NSNotification *)aNotification
{
  id <PCPreferences> prefs = [[project projectManager] prefController];

  ASSIGN(successSound, [prefs stringForKey:SuccessSound]);
  ASSIGN(failureSound, [prefs stringForKey:FailureSound]);

  ASSIGN(rootBuildDir, [prefs stringForKey:RootBuildDirectory]);
  ASSIGN(buildTool, [prefs stringForKey:BuildTool]);

  promptOnClean = [prefs boolForKey:PromptOnClean];
}

- (void)updateTargetField
{
  NSString *s;
  NSString *args;

  args = [[[project projectDict] objectForKey:PCBuilderArguments] 
    componentsJoinedByString:@" "];

  if (!args) args = @" ";

  s = [NSString stringWithFormat:@"%@ with args '%@'", buildTarget, args];

  [targetField setStringValue:s];
}

// --- Accessory
- (BOOL)isBuilding
{
  return _isBuilding;
}

- (BOOL)isCleaning
{
  return _isCleaning;
}

- (void)performStartBuild
{
  if (!_isBuilding && !_isCleaning)
    {
      [buildButton performClick:self];
    }
}

- (void)performStartClean
{
  if (!_isCleaning && !_isBuilding)
    {
      [cleanButton performClick:self];
    }
}

- (void)performStopBuild
{
  if (_isBuilding)
    {
      [buildButton performClick:self];
    }
  else if (_isCleaning)
    {
      [cleanButton performClick:self];
    }
}

- (NSArray *)buildArguments
{
  NSDictionary   *projectDict = [project projectDict];
  NSMutableArray *args = [NSMutableArray new];


  [args addObjectsFromArray:[projectDict objectForKey:PCBuilderArguments]];

  // --- Get arguments from options
  if ([[projectDict objectForKey:PCBuilderDebug] isEqualToString:@"YES"])
    { // there is no clear default; the default configuration of GNUstep-make
      // uses debug=no (since release 2.2.1, it had debug=yes before), but
      // that default can easily be changed at configuration time with the
      // --enable-debug-by-default configure option.
      [args addObject:@"debug=yes"];
    }
  else
    { // default is 'debug=yes'
      [args addObject:@"debug=no"];
    }
  if ([[projectDict objectForKey:PCBuilderStrip] isEqualToString:@"YES"])
    { // default is 'strip=no'
      [args addObject:@"strip=yes"];
    }
  if ([[projectDict objectForKey:PCBuilderSharedLibs] isEqualToString:@"NO"])
    { // default is 'shared=yes'
      [args addObject:@"shared=no"];
    }
  // Always add 'messages=yes' argument. Build output parsing assumes this.
  [args addObject:@"messages=yes"];
  // "Verbose ouput" option (Build Options panel) just toogle if build shows
  // as with argument 'messages=yes' or not.
  if ([[projectDict objectForKey:PCBuilderVerbose] isEqualToString:@"YES"])
    {
      verboseBuilding = YES;
    }
  else
    {
      verboseBuilding = NO;
    }

  return args;
}

// --- GUI Actions
- (void)startBuild:(id)sender
{
  if ([self stopMake:self] == YES)
    {// We've just stopped build process
      return;
    }

  // Set build arguments
  [buildArgs addObject:buildTarget];
  [buildArgs addObjectsFromArray:[self buildArguments]];
 
//  NSLog(@"ProjectBuilder arguments: %@", buildArgs);

  currentEL = ELNone;
  lastEL = ELNone;
  nextEL = ELNone;
  lastIndentString = @"";

  buildStatus = @"Building...";
  [buildStatusTarget setString:@"Build"];
  [cleanButton setEnabled:NO];
  _isBuilding = YES;
  [self build:self];
}

- (void)startClean:(id)sender
{
  if ([self stopMake:self] == YES)
    {// We've just stopped build process
      return;
    }

  if (promptOnClean)
    {
      if (NSRunAlertPanel(@"Project Clean",
			  @"Do you really want to clean project '%@'?",
			  @"Clean", @"Stop", nil, [project projectName])
	  == NSAlertAlternateReturn)
	{
	  [cleanButton setState:NSOffState];
	  return;
	}
    }

  // Set build arguments
  [buildArgs addObject:@"clean"];
  [buildArgs addObjectsFromArray:[self buildArguments]];

  buildStatus = @"Cleaning...";
  [buildStatusTarget setString:@"Clean"];
  [buildButton setEnabled:NO];
  _isCleaning = YES;
  [self build:self];
}

- (BOOL)stopMake:(id)sender
{
  if (makeTask && [makeTask isRunning])
    {
      PCLogStatus(self, @"task will terminate");
      NS_DURING
	{
	  [makeTask terminate];
	}
      NS_HANDLER
	{
	  return NO;
	}
      NS_ENDHANDLER
      return YES;
    }

  return NO;
}

- (void)showOptionsPanel:(id)sender
{
  [buildOptions show:[[componentView window] frame]];
}

- (void)cleanupAfterMake:(NSString *)statusString
{
//  NSString *statusString;

  if (_isBuilding || _isCleaning)
    {
//      statusString =[NSString stringWithFormat: 
//	@"%@ - %@ terminated", [project projectName], buildStatusTarget];
      [statusField setStringValue:statusString];
      [[project projectWindow] updateStatusLineWithText:statusString];
    }

  // Restore buttons state
  if (_isBuilding)
    {
      [buildButton setState:NSOffState];
      [cleanButton setEnabled:YES];
      _isBuilding = NO;
    }
  else if (_isCleaning)
    {
      [cleanButton setState:NSOffState];
      [buildButton setEnabled:YES];
      _isCleaning = NO;
    }

  [buildArgs removeAllObjects];
  [buildStatusTarget setString:@"Default"];

  // Initiated in [self build:]
  [currentBuildPath release];
  [currentBuildFile release];
}

// --- Actions
- (BOOL)prebuildCheck
{
  PCFileManager   *pcfm = [PCFileManager defaultManager];
  NSFileManager   *fm = [NSFileManager defaultManager];
  NSString        *buildDir;
  PCProjectEditor *projectEditor;
  int             ret;

  // Checking for project 'edited' state 
  if ([project isProjectChanged])
    {
      ret = NSRunAlertPanel(@"Project Build",
  			    @"Project was changed and not saved.\n"
  			    @"Do you want to save project before building it?",
  			    @"Stop Build", @"Save and Build", nil);
      switch (ret)
	{
	case NSAlertDefaultReturn: // Stop Build
	  return NO;
	  break;

	case NSAlertAlternateReturn: // Save Project
	  [project save];
	  break;
	}
    }
  else
    {
      // Synchronize PC.project and generate files
      [project save];
    }

  // Checking if edited files exist
  projectEditor = [project projectEditor];
  if ([projectEditor hasModifiedFiles])
    {
      if (!PCRunSaveModifiedFilesPanel(projectEditor, 
				       @"Save and Build",
				       @"Build Anyway",
				       @"Cancel"))
	{
	  return NO;
	}
    }

  // Check build tool path
  if (!buildTool || !([fm fileExistsAtPath:buildTool] || [fm fileExistsAtPath:[buildTool stringByAppendingPathExtension: @"exe"]]))
    {
      NSRunAlertPanel(@"Project Build",
  		      @"Build tool '%@' not found. Check preferences.\n"
		      @"Build will be terminated.",
  		      @"Close", nil, nil, buildTool);
      return NO;
    }

  // Create root build directory if not exist
  if (rootBuildDir && ![rootBuildDir isEqualToString:@""])
    {
      buildDir = [NSString 
	stringWithFormat:@"%@.build", [project projectName]];
      buildDir = [rootBuildDir stringByAppendingPathComponent:buildDir];
      if (![fm fileExistsAtPath:rootBuildDir] || 
	  ![fm fileExistsAtPath:buildDir])
	{
	  [pcfm createDirectoriesIfNeededAtPath:buildDir];
	}
    }

  return YES;
}

- (void)build:(id)sender
{
  // Make runtime vars
  // Released in [self cleanupAfterMake]
  currentBuildPath = [[NSMutableString alloc] 
    initWithString:[project projectPath]];
  currentBuildFile = [[NSMutableString alloc] initWithString:@""];

  // Checking build conditions
  if ([self prebuildCheck] == NO)
    {
      [self cleanupAfterMake:[NSString stringWithFormat: 
	@"%@ - %@ terminated", [project projectName], buildStatusTarget]];
      return;
    }

  // Prepearing to building
  stdOutPipe = [[NSPipe alloc] init];
  stdOutHandle = [stdOutPipe fileHandleForReading];

  stdErrorPipe = [[NSPipe alloc] init];
  stdErrorHandle = [stdErrorPipe fileHandleForReading];

  [errorsCountField setStringValue:@""];
  errorsCount = 0;
  warningsCount = 0;

  [statusField setStringValue:buildStatus];
  [[project projectWindow] updateStatusLineWithText:buildStatus];

  // Run make task
  [logOutput setString:@""];
  [errorArray removeAllObjects];
  [errorOutput reloadData];

  [NOTIFICATION_CENTER addObserver:self 
                          selector:@selector(buildDidTerminate:) 
			      name:NSTaskDidTerminateNotification
			    object:nil];

  makeTask = [[NSTask alloc] init];
  [makeTask setArguments:buildArgs];
  [makeTask setCurrentDirectoryPath:[project projectPath]];
  [makeTask setLaunchPath:buildTool];
  [makeTask setStandardOutput:stdOutPipe];
  [makeTask setStandardError:stdErrorPipe];

  [self logBuildString:
    [NSString stringWithFormat:@"=== %@ started ===", buildStatusTarget]
	       newLine:YES];

  NS_DURING
    {
      [makeTask launch];

      // now that we know that the task is running start logging
      [stdOutHandle waitForDataInBackgroundAndNotify];
      [NOTIFICATION_CENTER addObserver:self 
			      selector:@selector(logStdOut:)
				  name:NSFileHandleDataAvailableNotification
				object:stdOutHandle];
      _isLogging = YES;

      [stdErrorHandle waitForDataInBackgroundAndNotify];
      [NOTIFICATION_CENTER addObserver:self 
			      selector:@selector(logErrOut:) 
				  name:NSFileHandleDataAvailableNotification
				object:stdErrorHandle];
      _isErrorLogging = YES;
    }
  NS_HANDLER
    {
      NSRunAlertPanel(@"Problem Launching Build Tool",
		      [localException reason],
		      @"OK", nil, nil, nil);
		      
      //Clean up after task is terminated
      [NOTIFICATION_CENTER 
	postNotificationName:NSTaskDidTerminateNotification
	              object:makeTask];
    }
  NS_ENDHANDLER
}

- (void)buildDidTerminate:(NSNotification *)aNotif
{
  int      status;
  NSString *logString;
  NSString *statusString;

  if ([aNotif object] != makeTask)
    {
      return;
    }

//  NSLog(@"task did terminate");

  [NOTIFICATION_CENTER removeObserver:self 
			         name:NSTaskDidTerminateNotification
			       object:nil];

  // If task was not launched catch exception
  NS_DURING
    {
      status = [makeTask terminationStatus];
    }
  NS_HANDLER
    {
      status = 1;
    }
  NS_ENDHANDLER
 
  // Finish task
  // TODO: Strange behaviour of pipe and file handlers alloc/release. Also
  // they have big retain count here (2 or 3). Why? Notification retains it?
  RELEASE(makeTask);
  makeTask = nil;

  // Wait while logging ends
  while (_isLogging || _isErrorLogging) 
    {
      [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
			       beforeDate:[NSDate distantFuture]];
    }

  RELEASE(stdOutPipe);
  RELEASE(stdErrorPipe);

  [self updateErrorsCountField];

  if (status == 0)
    {
      logString = [NSString stringWithFormat:@"=== %@ succeeded! ===", 
		buildStatusTarget];
      statusString = [NSString stringWithFormat:@"%@ - %@ succeeded", 
		   [project projectName], buildStatusTarget];
    } 
  else
    {
      logString = [NSString stringWithFormat:@"=== %@ terminated! ===", 
		buildStatusTarget];
      if (errorsCount > 0)
	{
	  statusString = [NSString stringWithFormat: 
	    @"%@ - %@ failed (%i errors)", 
	    [project projectName], buildStatusTarget, errorsCount];
	}
      else
	{
	  statusString = [NSString stringWithFormat:@"%@ - %@ failed", 
		       [project projectName], buildStatusTarget];
	}
    }
  [statusField setStringValue:statusString];
  [[project projectWindow] updateStatusLineWithText:statusString];
  [self logBuildString:logString newLine:YES];

  // Run post process if configured
/*  if (status && postProcess)
    {
      [self performSelector:postProcess];
      postProcess = NULL;
    }*/

  [self cleanupAfterMake:statusString];
}

// --- BuilderOptions delegate
- (void)targetDidSet:(NSString *)target
{
  [buildTarget setString:target];
  [self updateTargetField];
}

@end

@implementation PCProjectBuilder (Logging)

- (void)updateErrorsCountField
{
  NSString *string;
  NSString *errorsString = @"";
  NSString *warningsString = @"";

  if (errorsCount > 0)
    {
      if (errorsCount > 1)
	{
	  errorsString = [NSString stringWithFormat:@"%i errors", 
		       errorsCount];
	}
      else
	{
	  errorsString = @"1 error";
	}
    }

  if (warningsCount > 0)
    {
      if (warningsCount > 1)
	{
	  warningsString = [NSString stringWithFormat:@"%i warnings", 
			 warningsCount];
	}
      else
	{
	  warningsString = @"1 warning";
	}
    }

  string = [NSString stringWithFormat:@"%@ %@", errorsString, warningsString];
  [errorsCountField setStringValue:string];
}

// --- Data notifications
// Both methods make call to dipatcher logData:error:
- (void)logStdOut:(NSNotification *)aNotif
{
  NSData *data;

  if ((data = [stdOutHandle availableData]) && [data length] > 0)
    {
      [self logData:data error:NO];
      [stdOutHandle waitForDataInBackgroundAndNotify];
    }
  else
    {
      // stop logging after the task has closed the pipe
      [NOTIFICATION_CENTER removeObserver:self 
			             name:NSFileHandleDataAvailableNotification
			           object:stdOutHandle];
      _isLogging = NO;
    }
}

- (void)logErrOut:(NSNotification *)aNotif
{
  NSData *data;

  if ((data = [stdErrorHandle availableData]) && [data length] > 0)
    {
      [self logData:data error:YES];
      [stdErrorHandle waitForDataInBackgroundAndNotify];
    }
  else
    {
      // stop logging after the task has closed the pipe
      [NOTIFICATION_CENTER removeObserver:self 
			             name:NSFileHandleDataAvailableNotification
			           object:stdErrorHandle];
      _isErrorLogging = NO;
    }
}

// --- Dispatching
- (void)logData:(NSData *)data
          error:(BOOL)isError
{
  NSString *dataString;
  NSRange  newLineRange;
  NSRange  lineRange;
  NSString *lineString;

  dataString = [[NSString alloc] 
    initWithData:data 
	encoding:[NSString defaultCStringEncoding]];
			    
  // Process new data
  lineRange.location = 0;
  newLineRange.location = 0;
  // 'errorString' collects data across logData:error: calls until 
  // new line character is appeared.
  [errorString appendString:dataString];
  while (newLineRange.location != NSNotFound)
    {
      newLineRange = [errorString rangeOfString:@"\n"];
/*      NSLog(@"Line(%i) new line range: %i,%i for string\n<--|%@|-->", 
	    [errorString length],
	    newLineRange.location, newLineRange.length, 
	    errorString);*/

      if (newLineRange.location < [errorString length])
	{
//  	  NSLog(@"<------%@------>", errorString);

	  lineRange.length = newLineRange.location+1;
	  lineString = [errorString substringWithRange:lineRange];
	  [errorString deleteCharactersInRange:lineRange];

	  // Send it to error view
	  // Do not process make errors in other mode but building. Maybe
	  // some day...
	  if (_isBuilding && isError)
	    {
    	      [self logErrorString:lineString];
	    }
	  // Cleaning or building standard out string
	  if (!isError || verboseBuilding)
	    {
	      [self logBuildString:lineString newLine:NO];
	    }
	}
      else
	{
	  newLineRange.location = NSNotFound;
	  continue;
	}
    }

  RELEASE(dataString);
}

@end

@implementation PCProjectBuilder (BuildLogging)

// --- Parsing utilities
- (BOOL)line:(NSString *)lineString startsWithString:(NSString *)substring
{
  NSInteger position = 0;
  NSRange   range = NSMakeRange(position,1);

  while ([[lineString substringWithRange:range] isEqualToString:@" "])
    {
      range.location = ++position;
    }

/*  NSLog(@"Line '%@' position: %i substring '%@'", 
	lineString, position, substring);*/

  range = [lineString rangeOfString:substring];
  if ((range.location == NSNotFound) ||
      (range.location != position))
    {
      return NO;
    }

  return YES;
}

// Clean leading spaces and return cleaned array of components
- (NSArray *)componentsOfLine:(NSString *)lineString
{
  NSArray        *lineComponents;
  NSMutableArray *tempComponents;

  lineComponents = [lineString componentsSeparatedByString:@" "];
  tempComponents = [NSMutableArray arrayWithArray:lineComponents];

  while ([[tempComponents objectAtIndex:0] isEqualToString:@""])
    {
      [tempComponents removeObjectAtIndex:0];
    }

  return tempComponents;
}

// Line starts with 'gmake' or 'make'.
// Changes 'currentBuildPath' if line starts with 
// "Entering directory" or "Leaving directory".
// For example: 
// gmake[1]: Entering directory '/Users/me/Project/Subproject.subproj'
- (void)parseMakeLine:(NSString *)lineString
{
  NSMutableArray *makeLineComponents;
  NSString       *makeLine;
  NSString       *pathComponent;
  NSString       *path;

  //  NSLog(@"parseMakeLine: %@", lineString);

  makeLineComponents = [NSMutableArray 
    arrayWithArray:[lineString componentsSeparatedByString:@" "]];

  // Don't check for item at index 0 contents (it's 'gmake[1]:' or 'make[1]:') 
  // just remove it.
  [makeLineComponents removeObjectAtIndex:0];
  makeLine = [makeLineComponents componentsJoinedByString:@" "];

  if ([self line:makeLine startsWithString:@"Entering directory"])
    {
      pathComponent = [makeLineComponents objectAtIndex:2];
      path = [pathComponent
	substringWithRange:NSMakeRange(1,[pathComponent length]-3)]; 
//      NSLog(@"Go down to %@", path);
      [currentBuildPath setString:path];
    }
  else if ([self line:makeLine startsWithString:@"Leaving directory"])
    {
//      NSLog(@"Go up from %@", [makeLineComponents objectAtIndex:2]);
      [currentBuildPath 
	setString:[currentBuildPath stringByDeletingLastPathComponent]];
    }
//  NSLog(@"Current build path: %@", currentBuildPath);
}

// Should return:
// 'Compiling ...'
// 'Linking ...'
// Also updates currentBuildFile
- (NSString *)parseCompilerLine:(NSString *)lineString
{
  NSArray  *lineComponents = [self componentsOfLine:lineString];
  NSString *outputString = nil;

  if ([lineComponents containsObject:@"-c"])
    {
      [currentBuildFile setString:[lineComponents objectAtIndex:1]];
      outputString = [NSString 
	stringWithFormat:@" Compiling %@...\n", currentBuildFile];
    }
  else if ([lineComponents containsObject:@"-rdynamic"])
    {
      outputString = [NSString 
	stringWithFormat:@" Linking %@...\n", 
	[lineComponents objectAtIndex:[lineComponents indexOfObject:@"-o"]+1]];
    }

  return outputString;
}
// --- Parsing utilities end

// Log output
- (void)logBuildString:(NSString *)string
	       newLine:(BOOL)newLine
{
  NSString *logString = [self parseBuildLine:string];

  if (!logString)
    {
      return;
    }

  [logOutput replaceCharactersInRange:
    NSMakeRange([[logOutput string] length],0) withString:logString];

  if (newLine)
    {
      [logOutput replaceCharactersInRange:
	NSMakeRange([[logOutput string] length], 0) withString:@"\n"];
    }

  [logOutput scrollRangeToVisible:NSMakeRange([[logOutput string] length], 0)];
  [logOutput setNeedsDisplay:YES];
}

// Standard out is parsed for detection of directory, file, etc.
// Gets complete line (ended with '\n') as argument
- (NSString *)parseBuildLine:(NSString *)string
{
  NSArray  *components = [self componentsOfLine:string];
  NSString *parsedString = nil;

  if (!components)
    {
      return nil;
    }

  if ([self line:string startsWithString:@"gmake"] ||
      [self line:string startsWithString:@"make"])
    {// Do current path detection
      [self parseMakeLine:string];
    }
  else if ([self line:string startsWithString:@"gcc"] ||
           [self line:string startsWithString:@"egcc"] ||
           [self line:string startsWithString:@"clang"])
    {// Parse compiler output
      parsedString = [self parseCompilerLine:string];
    }
  else if ([self line:string startsWithString:@"Making"] ||
	   [self line:string startsWithString:@"==="])
    {// It's a gnustep-make and self output
      parsedString = string;
    }

  if (parsedString && ![self line:parsedString startsWithString:@"==="])
    {
      [statusField setStringValue:parsedString];
      [[project projectWindow] updateStatusLineWithText:parsedString];
    }

  if (verboseBuilding)
    {
      return string;
    }
  else
    {
      return parsedString;
    }
}

@end

@implementation PCProjectBuilder (ErrorLogging)

// Entry point for error logging
- (void)logErrorString:(NSString *)string
{
  NSArray *items;

  items = [self parseErrorLine:string];
  if (items)
    {
      [errorArray addObjectsFromArray:items];
      [errorOutput reloadData];
      [errorOutput scrollRowToVisible:[errorArray count]-1];
    }
}

// Used for warning or error message retrieval
- (NSString *)lineTail:(NSString*)line afterString:(NSString*)string
{
  NSRange substrRange;

  substrRange = [line rangeOfString:string];
/*  NSLog(@"In function ':%i:%i", 
	substrRange.location, substrRange.length);*/
  substrRange.location += substrRange.length;
  substrRange.length = [line length] - (substrRange.location);
/*  NSLog(@"In function ':%i:%i", 
	substrRange.location, substrRange.length);*/

  return [line substringWithRange:substrRange];
}

- (NSArray *)parseErrorLine:(NSString *)string
{
  NSArray             *components = [string componentsSeparatedByString:@":"];
  NSString            *file = @"";
  NSString            *includedFile = @"";
  NSString            *position = @"{x=0; y=0}";
  NSString            *type = @"";
  NSString            *message = @"";
  NSMutableArray      *items = [NSMutableArray arrayWithCapacity:1];
  NSMutableDictionary *errorItem;
  NSString            *indentString = @"\t";
  NSString            *lastFile = @"";
  NSString            *lastIncludedFile = @"";

  NSAttributedString  *attributedString;
  NSMutableDictionary *attributes = [NSMutableDictionary new];
  NSFont              *font = [NSFont boldSystemFontOfSize:12.0];

  [attributes setObject:font forKey:NSFontAttributeName];
  [attributes setObject:[NSNumber numberWithInt:NSSingleUnderlineStyle] 
		 forKey:NSUnderlineStyleAttributeName];

  lastEL = currentEL;
  //  NSLog(@"error string: %@", string);
/*  if (lastEL == ELFile) NSLog(@"+++ELFile");
  if (lastEL == ELFunction) NSLog(@"+++ELFunction");
  if (lastEL == ELIncluded) NSLog(@"+++ELIncluded");
  if (lastEL == ELError) NSLog(@"+++ELError");
  if (lastEL == ELNone) NSLog(@"+++ELNone");*/
  //NSLog(@"components: %lu, %@", (unsigned long)[components count], components);
  if ([errorArray count] > 0)
    {
      lastFile = [[errorArray lastObject] objectForKey:@"File"];
      lastIncludedFile = [[errorArray lastObject] objectForKey:@"IncludedFile"];
    }

  if ([string rangeOfString:@"In file included from "].location != NSNotFound)
    {
      currentEL = ELIncluded;
      return nil;
    }
  else if ([string rangeOfString:@"In function '"].location != NSNotFound)
    {
      currentEL = ELFunction;
      return nil;
    }
  else if ([string rangeOfString:@" At top level:"].location != NSNotFound)
    {
      currentEL = ELFile;
      return nil;
    }
  else if ([components count] > 3)
    {
      NSUInteger typeIndex;
      NSString   *substr;

      // file and includedFile
      file = [currentBuildPath  
	stringByAppendingPathComponent:currentBuildFile];
      if (lastEL == ELIncluded 
	  || [[components objectAtIndex:0] isEqualToString:lastIncludedFile])
	{// first message after "In file included from"
//	  NSLog(@"Inlcuded File: %@", file);
	  includedFile = [components objectAtIndex:0];
      	  file = 
	    [currentBuildPath stringByAppendingPathComponent:includedFile];
	  currentEL = ELIncludedError;
	}
      else
	{
	  currentEL = ELError;
	}

      // type
      typeIndex = NSNotFound;
      if ((typeIndex = [components indexOfObject:@" warning"]) != NSNotFound)
	{
	  type = [components objectAtIndex:typeIndex];
	  warningsCount++;
	}
      else if ((typeIndex = [components indexOfObject:@" note"]) != NSNotFound) // generated by clang
	{
	  type = [components objectAtIndex:typeIndex];
	}
      else if ((typeIndex = [components indexOfObject:@" error"]) != NSNotFound)
	{
	  type = [components objectAtIndex:typeIndex];
	  errorsCount++;
	}
      else if ((typeIndex = [components indexOfObject:@" fatal error"]) != NSNotFound)
	{
	  type = [components objectAtIndex:typeIndex];
	  errorsCount++;
	}

      //     NSLog(@"typeIndex: %u", (unsigned int)typeIndex);
      // position
      if (typeIndex == 2) // :line:
	{
	  int      lInt = atoi([[components objectAtIndex:1] cString]);
	  NSNumber *lNumber = [NSNumber numberWithInt:lInt];

          //          NSLog(@"type 2, parsed l: %i", lInt);
	  position = [NSString stringWithFormat:@"{x=%i; y=0}", 
		   [lNumber intValue]];
	}
      else if (typeIndex == 3) // :line:column:
	{
	  int      lInt = atoi([[components objectAtIndex:1] cString]);
	  int      cInt = atoi([[components objectAtIndex:2] cString]);
	  NSNumber *lNumber = [NSNumber numberWithInt:lInt];
	  NSNumber *cNumber = [NSNumber numberWithInt:cInt];

          //          NSLog(@"type 3, parsed l,c: %i, %i", lInt, cInt);
	  position = [NSString stringWithFormat:@"{x=%i; y=%i}", 
	      	   [lNumber intValue], [cNumber intValue]];
	}
      // message
      substr = [NSString stringWithFormat:@"%@:", type];
      message = [self lineTail:string afterString:substr];
    }
  else
    {
      return nil;
    }

  // Insert indentation
  if (currentEL == ELError)
    {
      if (lastEL == ELFunction)
	{
	  indentString = @"\t\t";
	}
      else if (lastEL == ELError)
	{
	  indentString = [NSString stringWithString:lastIndentString];
	}
    }
  else if (currentEL == ELIncluded)
    {
      indentString = @"";
    }
/*  else if (currentEL == ELIncludedError)
    {
      indentString = @"\t\t";
    }*/

  message = [NSString stringWithFormat:@"%@%@", indentString, message];
  lastIndentString = [indentString copy];

  // Create array items
  if ((lastEL == ELNone || ![file isEqualToString:lastFile]) 
      && [includedFile isEqualToString:@""])
    {
//      NSLog(@"lastEL == ELNone (%@)", includedFile);
//      NSLog(@"File: %@ != %@", file, lastFile);
      errorItem = [NSMutableDictionary dictionaryWithCapacity:1];
      [errorItem setObject:@"" forKey:@"ErrorImage"];
      [errorItem setObject:[file copy] forKey:@"File"];
      [errorItem setObject:[includedFile copy] forKey:@"IncludedFile"];
      [errorItem setObject:@"" forKey:@"Position"];
      [errorItem setObject:@"" forKey:@"Type"];
  
      attributedString = [[NSAttributedString alloc] 
	initWithString:[file lastPathComponent]
	    attributes:attributes];
      [errorItem setObject:[attributedString copy] forKey:@"Error"];
      [attributedString release];

      [items addObject:errorItem];
    }

  if ((lastEL == ELIncluded || currentEL == ELIncludedError)
      && ![includedFile isEqualToString:lastIncludedFile])
    {
      NSString *incMessage = [NSString stringWithFormat:@"%@", includedFile];

//      NSLog(@"Included: %@ != %@", includedFile, lastIncludedFile);
      errorItem = [NSMutableDictionary dictionaryWithCapacity:1];
      [errorItem setObject:@"" forKey:@"ErrorImage"];
      [errorItem setObject:[file copy] forKey:@"File"];
      [errorItem setObject:[includedFile copy] forKey:@"IncludedFile"];
      [errorItem setObject:@"" forKey:@"Position"];
      [errorItem setObject:@"" forKey:@"Type"];

      attributedString = [[NSAttributedString alloc] initWithString:incMessage
							 attributes:attributes];
      [errorItem setObject:[attributedString copy] forKey:@"Error"];
      [attributedString release];

      [items addObject:errorItem];
    }

  errorItem = [NSMutableDictionary dictionaryWithCapacity:1];
  [errorItem setObject:@"" forKey:@"ErrorImage"];
  [errorItem setObject:[file copy] forKey:@"File"];
  [errorItem setObject:[includedFile copy] forKey:@"IncludedFile"];
  [errorItem setObject:[position copy] forKey:@"Position"];
  [errorItem setObject:[type copy] forKey:@"Type"];
  [errorItem setObject:[message copy] forKey:@"Error"];

//  NSLog(@"Parsed message:%@ (%@)", message, includedFile);

  [items addObject:errorItem];

  return items;
}

// --- Error output table delegate methods
- (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView
{
  if (errorArray != nil && aTableView == errorOutput)
    {
      return [errorArray count];
    }

  return 0;
}
    
- (id)            tableView:(NSTableView *)aTableView
  objectValueForTableColumn:(NSTableColumn *)aTableColumn
                        row:(NSInteger)rowIndex
{
  NSDictionary *errorItem;

  if (errorArray != nil && aTableView == errorOutput)
    {
      errorItem = [errorArray objectAtIndex:rowIndex];

      return [errorItem objectForKey:[aTableColumn identifier]];
    }

  return nil;
}

- (void)errorItemClick:(id)sender
{
  NSInteger       rowIndex = [errorOutput selectedRow];
  NSDictionary    *error = [errorArray objectAtIndex:rowIndex];
  NSPoint         position;
  PCProjectEditor *projectEditor = [project projectEditor];
  id<CodeEditor>  editor;

  editor = [projectEditor openEditorForFile:[error objectForKey:@"File"]
				   editable:YES
				   windowed:NO];
  if (editor)
    {
      // TODO / FIXME using a NSPoint here is weak since it is Float vs. integer line numbers
      position = NSPointFromString([error objectForKey:@"Position"]);
      [projectEditor orderFrontEditorForFile:[error objectForKey:@"File"]];
      [editor scrollToLineNumber:(NSUInteger)position.x];

/*      NSLog(@"%i: %@(%@): %@", 
	    position.x, 
	    [error objectForKey:@"File"], 
	    [error objectForKey:@"IncludedFile"],
	    [error objectForKey:@"Error"]);*/
    }
}

@end