BWToolkit / BWSplitView.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
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
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
//
//  BWSplitView.m
//  BWToolkit
//
//  Created by Brandon Walkin (www.brandonwalkin.com) and Fraser Kuyvenhoven.
//  All code is provided under the New BSD license.
//

#import "BWSplitView.h"
#import "BWAnchoredButtonBar.h"
#import "NSColor+BWAdditions.h"
#import "NSEvent+BWAdditions.h"

static NSGradient *gradient;
static NSImage *dimpleImageBitmap, *dimpleImageVector;
static NSColor *borderColor, *gradientStartColor, *gradientEndColor;
static float scaleFactor = 1.0f;

#define dimpleDimension 4.0f

#define RESIZE_DEBUG_LOGS 0

@interface BWSplitView (BWSVPrivate)

- (void)drawDimpleInRect:(NSRect)aRect;
- (void)drawGradientDividerInRect:(NSRect)aRect;
- (int)resizableSubviews;
- (BOOL)subviewIsResizable:(NSView *)subview;

- (BOOL)subviewIsCollapsible:(NSView *)subview;
- (BOOL)subviewIsCollapsed:(NSView *)subview;
- (int)collapsibleSubviewIndex;
- (NSView *)collapsibleSubview;
- (BOOL)hasCollapsibleSubview;
- (BOOL)collapsibleSubviewIsCollapsed;

- (CGFloat)subviewMinimumSize:(int)subviewIndex;
- (CGFloat)subviewMaximumSize:(int)subviewIndex;

- (void)recalculatePreferredProportionsAndSizes;
- (BOOL)validatePreferredProportionsAndSizes;
- (void)validateAndCalculatePreferredProportionsAndSizes;
- (void)clearPreferredProportionsAndSizes;

- (void)resizeAndAdjustSubviews;

@end

@interface BWSplitView ()
@property BOOL checkboxIsEnabled;
@end

@implementation BWSplitView

@synthesize color, colorIsEnabled, checkboxIsEnabled, minValues, maxValues, minUnits, maxUnits, collapsiblePopupSelection, dividerCanCollapse, collapsibleSubviewCollapsed;
@synthesize resizableSubviewPreferredProportion, nonresizableSubviewPreferredSize, stateForLastPreferredCalculations;
@synthesize toggleCollapseButton, secondaryDelegate;

+ (void)initialize;
{
    borderColor        = [[NSColor colorWithCalibratedWhite:(165.0f / 255.0f) alpha:1] retain];
    gradientStartColor = [[NSColor colorWithCalibratedWhite:(253.0f / 255.0f) alpha:1] retain];
    gradientEndColor   = [[NSColor colorWithCalibratedWhite:(222.0f / 255.0f) alpha:1] retain];

    gradient           = [[NSGradient alloc] initWithStartingColor:gradientStartColor endingColor:gradientEndColor];

	NSBundle *bundle = [NSBundle bundleForClass:[BWSplitView class]];
	dimpleImageBitmap  = [[NSImage alloc] initWithContentsOfFile:[bundle pathForImageResource:@"GradientSplitViewDimpleBitmap.tif"]];
	dimpleImageVector  = [[NSImage alloc] initWithContentsOfFile:[bundle pathForImageResource:@"GradientSplitViewDimpleVector.pdf"]];
    [dimpleImageBitmap setFlipped:YES];
	[dimpleImageVector setFlipped:YES];
}

- (id)initWithCoder:(NSCoder *)decoder;
{
    if ((self = [super initWithCoder:decoder]) != nil)
	{
		[self setColor:[decoder decodeObjectForKey:@"BWSVColor"]];
		[self setColorIsEnabled:[decoder decodeBoolForKey:@"BWSVColorIsEnabled"]];
		[self setMinValues:[decoder decodeObjectForKey:@"BWSVMinValues"]];
		[self setMaxValues:[decoder decodeObjectForKey:@"BWSVMaxValues"]];
		[self setMinUnits:[decoder decodeObjectForKey:@"BWSVMinUnits"]];
		[self setMaxUnits:[decoder decodeObjectForKey:@"BWSVMaxUnits"]];
		[self setCollapsiblePopupSelection:[decoder decodeIntForKey:@"BWSVCollapsiblePopupSelection"]];
		[self setDividerCanCollapse:[decoder decodeBoolForKey:@"BWSVDividerCanCollapse"]];
		
		// Delegate set in nib has been decoded, but we want that to be the secondary delegate
		[self setDelegate:[super delegate]];
		[super setDelegate:self];
	}
	return self;
}

- (void)encodeWithCoder:(NSCoder*)coder
{
	// Temporarily change delegate
	[super setDelegate:secondaryDelegate];
	
    [super encodeWithCoder:coder];
	
	[coder encodeObject:[self color] forKey:@"BWSVColor"];
	[coder encodeBool:[self colorIsEnabled] forKey:@"BWSVColorIsEnabled"];
	[coder encodeObject:[self minValues] forKey:@"BWSVMinValues"];
	[coder encodeObject:[self maxValues] forKey:@"BWSVMaxValues"];
	[coder encodeObject:[self minUnits] forKey:@"BWSVMinUnits"];
	[coder encodeObject:[self maxUnits] forKey:@"BWSVMaxUnits"];
	[coder encodeInt:[self collapsiblePopupSelection] forKey:@"BWSVCollapsiblePopupSelection"];
	[coder encodeBool:[self dividerCanCollapse] forKey:@"BWSVDividerCanCollapse"];
	
	// Set delegate back
	[self setDelegate:[super delegate]];
	[super setDelegate:self];
}

- (void)awakeFromNib
{
	scaleFactor = [[NSScreen mainScreen] userSpaceScaleFactor];
}

- (void)drawDividerInRect:(NSRect)aRect
{	
    if ([self isVertical])
    {
		aRect.size.width = [self dividerThickness];
		
		if (colorIsEnabled && color != nil)
			[color drawSwatchInRect:aRect];
		else
			[super drawDividerInRect:aRect];
    }
	else
	{
		aRect.size.height = [self dividerThickness];
		
		if ([self dividerThickness] <= 1.01)
		{
			if (colorIsEnabled && color != nil)
				[color drawSwatchInRect:aRect];
			else
				[super drawDividerInRect:aRect];
		}
		else
		{
			[self drawGradientDividerInRect:aRect];
		}
	}
}

- (void)drawGradientDividerInRect:(NSRect)aRect
{	
	aRect = [self centerScanRect:aRect];

	// Draw gradient
	NSRect gradRect = NSMakeRect(aRect.origin.x,aRect.origin.y + 1 / scaleFactor,aRect.size.width,aRect.size.height - 1 / scaleFactor);
	[gradient drawInRect:gradRect angle:90];
	
	// Draw top and bottom borders
	[borderColor bwDrawPixelThickLineAtPosition:0 withInset:0 inRect:aRect inView:self horizontal:YES flip:NO];
	[borderColor bwDrawPixelThickLineAtPosition:0 withInset:0 inRect:aRect inView:self horizontal:YES flip:YES];
	
	[self drawDimpleInRect:aRect];
}

- (void)drawDimpleInRect:(NSRect)aRect
{
    float startY = aRect.origin.y + roundf((aRect.size.height / 2) - (dimpleDimension / 2));
    float startX = aRect.origin.x + roundf((aRect.size.width / 2) - (dimpleDimension / 2));
    NSRect destRect = NSMakeRect(startX,startY,dimpleDimension,dimpleDimension);
	
	// Draw at pixel bounds 
	destRect = [self convertRectToBase:destRect];
	destRect.origin.x = floor(destRect.origin.x);
	
	double param, fractPart, intPart;
	param = destRect.origin.y;
	fractPart = modf(param, &intPart);
	if (fractPart < 0.99)
		destRect.origin.y = floor(destRect.origin.y);
	destRect = [self convertRectFromBase:destRect];
	
	if (scaleFactor == 1)
	{
		NSRect dimpleRect = NSMakeRect(0,0,dimpleDimension,dimpleDimension);
		[dimpleImageBitmap drawInRect:destRect fromRect:dimpleRect operation:NSCompositeSourceOver fraction:1];
	}
    else
	{
		NSRect dimpleRect = NSMakeRect(0,0,[dimpleImageVector size].width,[dimpleImageVector size].height);
		[dimpleImageVector drawInRect:destRect fromRect:dimpleRect operation:NSCompositeSourceOver fraction:1];
	}
}

- (CGFloat)dividerThickness
{
	float thickness;
	
    if ([self isVertical])
	{
		thickness = 1;
	}
	else
	{
		if ([super dividerThickness] < 1.01)
			thickness = 1;
		else
			thickness = 10;
	}
	
    return thickness;
}

- (void)setDelegate:(id)anObj
{
	if (secondaryDelegate != self)
		secondaryDelegate = anObj;
	else
		secondaryDelegate = nil;
}

- (BOOL)subviewIsCollapsible:(NSView *)subview;
{
	// check if this is the collapsible subview
	int subviewIndex = [[self subviews] indexOfObject:subview];
	
	BOOL isCollapsibleSubview = (([self collapsiblePopupSelection] == 1 && subviewIndex == 0) || ([self collapsiblePopupSelection] == 2 && subviewIndex == [[self subviews] count] - 1));
	
	return isCollapsibleSubview;
}

- (BOOL)subviewIsCollapsed:(NSView *)subview;
{
	BOOL isCollapsibleSubview = [self subviewIsCollapsible:subview];
	
	return [super isSubviewCollapsed:subview] || (isCollapsibleSubview && collapsibleSubviewCollapsed);
}

- (BOOL)collapsibleSubviewIsCollapsed;
{
	return [self subviewIsCollapsed:[self collapsibleSubview]];
}

- (int)collapsibleSubviewIndex;
{
	switch ([self collapsiblePopupSelection]) {
		case 1:
			return 0;
			break;
		case 2:
			return [[self subviews] count] - 1;
			break;
		default:
			return -1;
			break;
	}
}

- (NSView *)collapsibleSubview;
{
	int index = [self collapsibleSubviewIndex];
	
	if (index >= 0)
		return [[self subviews] objectAtIndex:index];
	else
		return nil;
}

- (BOOL)hasCollapsibleSubview;
{
	if ([self respondsToSelector:@selector(ibDidAddToDesignableDocument:)])
		return NO;
	
	return [self collapsiblePopupSelection] != 0;
}

// This is done to support the use of Core Animation to collapse subviews
- (void)adjustSubviews
{
	[super adjustSubviews];
	[[self window] invalidateCursorRectsForView:self];
}

- (void)setCollapsibleSubviewCollapsedHelper:(NSNumber *)flag
{
	[self setCollapsibleSubviewCollapsed:[flag boolValue]];
}

- (void)animationEnded
{
	isAnimating = NO;
}

- (float)animationDuration
{
	if ([NSEvent bwShiftKeyIsDown])
		return 2.0;
	
	return 0.25;
}

- (BOOL)hasCollapsibleDivider
{
	if ([self hasCollapsibleSubview] && (dividerCanCollapse || [self dividerThickness] < 1.01))
		return YES;
	
	return NO;
}

- (int)collapsibleDividerIndex
{
	if ([self hasCollapsibleDivider])
	{
		if ([self collapsiblePopupSelection] == 1)
			return 0;
		else if ([self collapsiblePopupSelection] == 2)
			return [self subviews].count - 2;
	}
	
	return -1;
}

- (void)setCollapsibleSubviewCollapsed:(BOOL)flag
{
	collapsibleSubviewCollapsed = flag;

	if (flag)
		[[self toggleCollapseButton] setState:0];
	else
		[[self toggleCollapseButton] setState:1];	
}

- (void)setMinSizeForCollapsibleSubview:(NSNumber *)minSize
{
	if ([self hasCollapsibleSubview])
	{
		NSMutableDictionary *tempMinValues = [[self minValues] mutableCopy];
		[tempMinValues setObject:minSize forKey:[NSNumber numberWithInt:[[self subviews] indexOfObject:[self collapsibleSubview]]]];
		[self setMinValues:tempMinValues];
	}
}

- (void)removeMinSizeForCollapsibleSubview
{
	if ([self hasCollapsibleSubview])
	{
		NSMutableDictionary *tempMinValues = [[self minValues] mutableCopy];
		[tempMinValues removeObjectForKey:[NSNumber numberWithInt:[[self subviews] indexOfObject:[self collapsibleSubview]]]];
		[self setMinValues:tempMinValues];
	}
}

- (void)restoreAutoresizesSubviews:(NSNumber *)flag
{
	[[self collapsibleSubview] setAutoresizesSubviews:[flag boolValue]];
}

- (IBAction)toggleCollapse:(id)sender
{
	if ([self respondsToSelector:@selector(ibDidAddToDesignableDocument:)])
		return;
	
	if ([self hasCollapsibleSubview] == NO || [self collapsibleSubview] == nil)
		return;
	
	if (isAnimating)
		return;
	
	
	// Check to see if the collapsible subview has a minimum width/height and record it.
	// We'll later remove the min size temporarily while animating and then restore it.
	BOOL hasMinSize = NO;
	NSNumber *minSize = [minValues objectForKey:[NSNumber numberWithInt:[[self subviews] indexOfObject:[self collapsibleSubview]]]];
	minSize = [[minSize copy] autorelease];
	
	if (minSize != nil || [minSize intValue] != 0)
		hasMinSize = YES;
	
	
	// Get a reference to the button and modify its behavior
	if ([self toggleCollapseButton] == nil)
	{
		[self setToggleCollapseButton:sender];

		[[toggleCollapseButton cell] setHighlightsBy:NSPushInCellMask];
		[[toggleCollapseButton cell] setShowsStateBy:NSContentsCellMask];
	}
	
	
	// Temporary: For simplicty, there should only be 1 subview other than the collapsible subview that's resizable for the collapse to happen
	NSView *resizableSubview = nil;
	
	for (NSView *subview in [self subviews])
	{
		if ([self subviewIsResizable:subview] && subview != [self collapsibleSubview])
		{
			resizableSubview = subview;
		}
			
	}
	
	if (resizableSubview == nil)
		return;
	
	// Record whether the collapsible subview is set to autoresize subviews so we can restore it after the animation
	BOOL autoresizesSubviews = [[self collapsibleSubview] autoresizesSubviews];
	
	// Turn off autoresizesSubviews on the collapsible subview
	[[self collapsibleSubview] setAutoresizesSubviews:NO];
	
	// Get the thickness of the collapsible divider. If the divider cannot collapse, we set it to 0 so it doesn't affect our calculations.
	float collapsibleDividerThickness = [self dividerThickness];
	
	if ([self hasCollapsibleDivider] == NO)
		collapsibleDividerThickness = 0;
	
	// Collapsing by dragging the divider sets the view to be hidden, so unhide it
	[[self collapsibleSubview] setHidden:NO];
	
	if ([self isVertical])
	{
		float constantHeight = [self collapsibleSubview].frame.size.height;
		
		if ([self collapsibleSubviewCollapsed] == NO)
		{
			uncollapsedSize = [self collapsibleSubview].frame.size.width;
			
			if (hasMinSize)
				[self removeMinSizeForCollapsibleSubview];
			
			[NSAnimationContext beginGrouping];
			[[NSAnimationContext currentContext] setDuration:([self animationDuration])];			
			[[[self collapsibleSubview] animator] setFrameSize:NSMakeSize(0.0, constantHeight)];
			[[resizableSubview animator] setFrameSize:NSMakeSize(resizableSubview.frame.size.width + uncollapsedSize + collapsibleDividerThickness, constantHeight)];
			[NSAnimationContext endGrouping];
			
			if (hasMinSize)
				[self performSelector:@selector(setMinSizeForCollapsibleSubview:) withObject:minSize afterDelay:[self animationDuration]];
			
			[self performSelector:@selector(setCollapsibleSubviewCollapsedHelper:) withObject:[NSNumber numberWithBool:YES] afterDelay:[self animationDuration]];
		}
		else
		{
			if (hasMinSize)
				[self removeMinSizeForCollapsibleSubview];
			
			[NSAnimationContext beginGrouping];
			[[NSAnimationContext currentContext] setDuration:([self animationDuration])];
			[[[self collapsibleSubview] animator] setFrameSize:NSMakeSize(uncollapsedSize, constantHeight)];
			[[resizableSubview animator] setFrameSize:NSMakeSize(resizableSubview.frame.size.width - uncollapsedSize - collapsibleDividerThickness, constantHeight)];
			[NSAnimationContext endGrouping];
	
			if (hasMinSize)
				[self performSelector:@selector(setMinSizeForCollapsibleSubview:) withObject:minSize afterDelay:[self animationDuration]];
			
			[self setCollapsibleSubviewCollapsed:NO];
		}
	}
	else
	{
		float constantWidth = [self collapsibleSubview].frame.size.width;
		
		if ([self collapsibleSubviewCollapsed] == NO)
		{
			uncollapsedSize = [self collapsibleSubview].frame.size.height;
			
			if (hasMinSize)
				[self removeMinSizeForCollapsibleSubview];
			
			[NSAnimationContext beginGrouping];
			[[NSAnimationContext currentContext] setDuration:([self animationDuration])];			
			[[[self collapsibleSubview] animator] setFrameSize:NSMakeSize(constantWidth, 0.0)];
			[[resizableSubview animator] setFrameSize:NSMakeSize(constantWidth, resizableSubview.frame.size.height + uncollapsedSize + collapsibleDividerThickness)];
			[NSAnimationContext endGrouping];
			
			if (hasMinSize)
				[self performSelector:@selector(setMinSizeForCollapsibleSubview:) withObject:minSize afterDelay:[self animationDuration]];
			
			[self performSelector:@selector(setCollapsibleSubviewCollapsedHelper:) withObject:[NSNumber numberWithBool:YES] afterDelay:[self animationDuration]];
		}
		else
		{
			if (hasMinSize)
				[self removeMinSizeForCollapsibleSubview];
			
			[NSAnimationContext beginGrouping];
			[[NSAnimationContext currentContext] setDuration:([self animationDuration])];
			[[[self collapsibleSubview] animator] setFrameSize:NSMakeSize(constantWidth, uncollapsedSize)];
			[[resizableSubview animator] setFrameSize:NSMakeSize(constantWidth, resizableSubview.frame.size.height - uncollapsedSize - collapsibleDividerThickness)];
			[NSAnimationContext endGrouping];
			
			if (hasMinSize)
				[self performSelector:@selector(setMinSizeForCollapsibleSubview:) withObject:minSize afterDelay:[self animationDuration]];
			
			[self setCollapsibleSubviewCollapsed:NO];
		}
	}
	
	isAnimating = YES;
	[self performSelector:@selector(animationEnded) withObject:nil afterDelay:[self animationDuration]];
	[self performSelector:@selector(restoreAutoresizesSubviews:) withObject:[NSNumber numberWithBool:autoresizesSubviews] afterDelay:[self animationDuration]];
	
	[self performSelector:@selector(resizeAndAdjustSubviews) withObject:nil afterDelay:[self animationDuration]];
}

#pragma mark Mouse Tracking Methods

- (void)mouseDown:(NSEvent *)theEvent
{
	// Set the uncollapsed size whenever the split view is clicked or a drag has began. This lets us uncollapse to the size of the subview before the drag-collapse.
	if ([self hasCollapsibleSubview])
	{
		CGFloat collapsibleViewSize = [self isVertical] ?  [self collapsibleSubview].frame.size.width : [self collapsibleSubview].frame.size.height;
	
		if (!isAnimating && collapsibleViewSize > 0)
			uncollapsedSize = collapsibleViewSize;
	}

	[super mouseDown:theEvent];
}

#pragma mark NSSplitView Delegate Methods

- (BOOL)splitView:(NSSplitView *)splitView shouldHideDividerAtIndex:(NSInteger)dividerIndex
{
	if ([secondaryDelegate respondsToSelector:@selector(splitView:shouldHideDividerAtIndex:)] &&
		[secondaryDelegate isKindOfClass:[BWAnchoredButtonBar class]] == NO)
		return [secondaryDelegate splitView:splitView shouldHideDividerAtIndex:dividerIndex];
	
	if ([self respondsToSelector:@selector(ibDidAddToDesignableDocument:)] == NO)
	{
		if ([self hasCollapsibleDivider] && [self collapsibleDividerIndex] == dividerIndex)
		{
			[self setDividerCanCollapse:YES];
			return YES;
		}
	}

	return NO;
}

- (NSRect)splitView:(NSSplitView *)splitView additionalEffectiveRectOfDividerAtIndex:(NSInteger)dividerIndex
{
	if ([secondaryDelegate respondsToSelector:@selector(splitView:additionalEffectiveRectOfDividerAtIndex:)])
		return [secondaryDelegate splitView:splitView additionalEffectiveRectOfDividerAtIndex:dividerIndex];
	
	return NSZeroRect;
}

- (BOOL)splitView:(NSSplitView *)sender canCollapseSubview:(NSView *)subview
{
	if ([secondaryDelegate respondsToSelector:@selector(splitView:canCollapseSubview:)] &&
		[secondaryDelegate isKindOfClass:[BWAnchoredButtonBar class]] == NO)
		return [secondaryDelegate splitView:sender canCollapseSubview:subview];
	
	int subviewIndex = [[self subviews] indexOfObject:subview];
	
	if ([self respondsToSelector:@selector(ibDidAddToDesignableDocument:)] == NO)
	{
		if ([self collapsiblePopupSelection] == 1 && subviewIndex == 0)
			return YES;
		else if ([self collapsiblePopupSelection] == 2 && subviewIndex == [[self subviews] count] - 1)
			return YES;
	}
	
	return NO;
}

- (BOOL)splitView:(NSSplitView *)splitView shouldCollapseSubview:(NSView *)subview forDoubleClickOnDividerAtIndex:(NSInteger)dividerIndex
{
	if ([secondaryDelegate respondsToSelector:@selector(splitView:shouldCollapseSubview:forDoubleClickOnDividerAtIndex:)] &&
		[secondaryDelegate isKindOfClass:[BWAnchoredButtonBar class]] == NO)
		return [secondaryDelegate splitView:splitView shouldCollapseSubview:subview forDoubleClickOnDividerAtIndex:dividerIndex];
	
	int subviewIndex = [[self subviews] indexOfObject:subview];
	
	if ([self respondsToSelector:@selector(ibDidAddToDesignableDocument:)] == NO)
	{
		if (([self collapsiblePopupSelection] == 1 && subviewIndex == 0 && dividerIndex == 0) ||
			([self collapsiblePopupSelection] == 2 && subviewIndex == [[self subviews] count] - 1 && dividerIndex == [[splitView subviews] count] - 2))
		{
			if ([self isVertical])
				uncollapsedSize = [self collapsibleSubview].frame.size.width;
			else
				uncollapsedSize = [self collapsibleSubview].frame.size.height;
			
			[self setCollapsibleSubviewCollapsed:YES];
			
			// Cause the collapse ourselves by calling the resize method
			[self resizeAndAdjustSubviews];
			[self setNeedsDisplay:YES];
			
			// Since we manually did the resize above, we pretend that we don't want to collapse
			return NO;
		}
	}
	
	return NO;
}

- (CGFloat)splitView:(NSSplitView *)sender constrainMaxCoordinate:(CGFloat)proposedMax ofSubviewAt:(NSInteger)offset
{
	if ([secondaryDelegate respondsToSelector:@selector(splitView:constrainMaxCoordinate:ofSubviewAt:)] &&
		[secondaryDelegate isKindOfClass:[BWAnchoredButtonBar class]] == NO)
		return [secondaryDelegate splitView:sender constrainMaxCoordinate:proposedMax ofSubviewAt:offset];
	
	// Max coordinate depends on max of subview offset, and the min of subview offset + 1
	CGFloat newMaxFromThisSubview = proposedMax;
	CGFloat newMaxFromNextSubview = proposedMax;
	
	// Max from this subview
	CGFloat maxValue = [self subviewMaximumSize:offset];
	if (maxValue != FLT_MAX)
	{
		NSView *subview = [[self subviews] objectAtIndex:offset];
		CGFloat originCoord = [self isVertical] ? [subview frame].origin.x : [subview frame].origin.y;
		
		newMaxFromThisSubview = originCoord + maxValue;
	}
	
	// Max from the next subview
	int nextOffset = offset + 1;
	if ([[self subviews] count] > nextOffset)
	{
		CGFloat minValue = [self subviewMinimumSize:nextOffset];
		if (minValue != 0)
		{
			NSView *subview = [[self subviews] objectAtIndex:nextOffset];
			CGFloat endCoord = [self isVertical] ? [subview frame].origin.x + [subview frame].size.width : [subview frame].origin.y + [subview frame].size.height;
			
			newMaxFromNextSubview = endCoord - minValue - [self dividerThickness];
			// This could cause trouble when over constrained (TODO)
		}
	}
	
	CGFloat newMax = fminf(newMaxFromThisSubview, newMaxFromNextSubview);
	
	if (newMax < proposedMax)
		return newMax;
	
	return proposedMax;
}

- (CGFloat)splitView:(NSSplitView *)sender constrainMinCoordinate:(CGFloat)proposedMin ofSubviewAt:(NSInteger)offset
{
	if ([secondaryDelegate respondsToSelector:@selector(splitView:constrainMinCoordinate:ofSubviewAt:)] &&
		[secondaryDelegate isKindOfClass:[BWAnchoredButtonBar class]] == NO)
		return [secondaryDelegate splitView:sender constrainMinCoordinate:proposedMin ofSubviewAt:offset];
	
	// Min coordinate depends on min of subview offset and the max of subview offset + 1
	CGFloat newMinFromThisSubview = proposedMin;
	CGFloat newMaxFromNextSubview = proposedMin;
	
	// Min from this subview
	CGFloat minValue = [self subviewMinimumSize:offset];
	if (minValue != 0)
	{
		NSView *subview = [[self subviews] objectAtIndex:offset];
		CGFloat originCoord = [self isVertical] ? [subview frame].origin.x : [subview frame].origin.y;
		
		newMinFromThisSubview = originCoord + minValue;
	}
	
	// Min from the next subview
	int nextOffset = offset + 1;
	if ([[self subviews] count] > nextOffset)
	{
		CGFloat maxValue = [self subviewMaximumSize:nextOffset];
		if (maxValue != FLT_MAX)
		{
			NSView *subview = [[self subviews] objectAtIndex:nextOffset];
			CGFloat endCoord = [self isVertical] ? [subview frame].origin.x + [subview frame].size.width : [subview frame].origin.y + [subview frame].size.height;
			
			newMaxFromNextSubview = endCoord - maxValue - [self dividerThickness];
			// This could cause trouble when over constrained (TODO)
		}
	}
	
	CGFloat newMin = fmaxf(newMinFromThisSubview, newMaxFromNextSubview);
	
	if (newMin > proposedMin)
		return newMin;
	
	return proposedMin;
}

- (CGFloat)splitView:(NSSplitView *)sender constrainSplitPosition:(CGFloat)proposedPosition ofSubviewAt:(NSInteger)offset
{
	[self clearPreferredProportionsAndSizes];
	
	if ([self respondsToSelector:@selector(ibDidAddToDesignableDocument:)])
		return proposedPosition;	
	
	if ([secondaryDelegate respondsToSelector:@selector(splitView:constrainSplitPosition:ofSubviewAt:)] &&
		[secondaryDelegate isKindOfClass:[BWAnchoredButtonBar class]] == NO)
		return [secondaryDelegate splitView:sender constrainSplitPosition:proposedPosition ofSubviewAt:offset];
	
	return proposedPosition;
}

- (NSRect)splitView:(NSSplitView *)splitView effectiveRect:(NSRect)proposedEffectiveRect forDrawnRect:(NSRect)drawnRect ofDividerAtIndex:(NSInteger)dividerIndex
{
	if ([secondaryDelegate respondsToSelector:@selector(splitView:effectiveRect:forDrawnRect:ofDividerAtIndex:)])
		return [secondaryDelegate splitView:splitView effectiveRect:proposedEffectiveRect forDrawnRect:drawnRect ofDividerAtIndex:dividerIndex];
	
	return proposedEffectiveRect;
}

- (void)splitViewDidResizeSubviews:(NSNotification *)aNotification
{
	if (collapsibleSubviewCollapsed && ([self isVertical] ? [[self collapsibleSubview] frame].size.width > 0 : [[self collapsibleSubview] frame].size.height > 0))
	{
		[self setCollapsibleSubviewCollapsed:NO];

		[self resizeAndAdjustSubviews];
	}
	else if (!collapsibleSubviewCollapsed && ([self isVertical] ? [[self collapsibleSubview] frame].size.width < 0.1 : [[self collapsibleSubview] frame].size.height < 0.1))
	{
		[self setCollapsibleSubviewCollapsed:YES];

		[self resizeAndAdjustSubviews];
	}
	else if ([self collapsibleSubviewIsCollapsed])
	{
		[self resizeAndAdjustSubviews];
	}
	
	[self setNeedsDisplay:YES];
	
	if ([secondaryDelegate respondsToSelector:@selector(splitViewDidResizeSubviews:)])
		[secondaryDelegate splitViewDidResizeSubviews:aNotification];
}

- (void)splitViewWillResizeSubviews:(NSNotification *)aNotification
{
	if ([secondaryDelegate respondsToSelector:@selector(splitViewWillResizeSubviews:)])
		[secondaryDelegate splitViewWillResizeSubviews:aNotification];
}

#pragma mark - Resize Subviews Delegate Method and Helper Methods

- (int)resizableSubviews
{
	int resizableSubviews = 0;
	
	for (NSView *subview in [self subviews])
	{
		if ([self subviewIsResizable:subview])
			resizableSubviews++;
	}
	
	return resizableSubviews;
}

- (BOOL)subviewIsResizable:(NSView *)subview
{
	if ([self isVertical] && [subview autoresizingMask] & NSViewWidthSizable)
		return YES;
	
	if (![self isVertical] && [subview autoresizingMask] & NSViewHeightSizable)
		return YES;
	
	return NO;
}

- (CGFloat)subviewMinimumSize:(int)subviewIndex;
{
	NSNumber *minNum = [minValues objectForKey:[NSNumber numberWithInt:subviewIndex]];
	if (!minNum)
		return 0;
	
	int units = 0;
	NSNumber *unitsNum = [minUnits objectForKey:[NSNumber numberWithInt:subviewIndex]];
	if (unitsNum)
		units = [unitsNum intValue];
	
	CGFloat min = [minNum floatValue];
	
	switch (units)
	{
		case 1:
		{
			// Percent
			CGFloat dividerThicknessTotal = [self dividerThickness] * ([[self subviews] count] - 1);
			CGFloat totalSize = [self isVertical] ? [self frame].size.width : [self frame].size.height;
			totalSize -= dividerThicknessTotal;
			
			return roundf((min / 100.0) * totalSize);
			break;
		}
		case 0:
		default:
		{
			// Points
			return min;
			break;
		}
	}
}

- (CGFloat)subviewMaximumSize:(int)subviewIndex;
{
	NSNumber *maxNum = [maxValues objectForKey:[NSNumber numberWithInt:subviewIndex]];
	if (!maxNum)
		return FLT_MAX;
	
	int units = 0;
	NSNumber *unitsNum = [maxUnits objectForKey:[NSNumber numberWithInt:subviewIndex]];
	if (unitsNum)
		units = [unitsNum intValue];
	
	CGFloat max = [maxNum floatValue];
	
	switch (units)
	{
		case 1:
		{
			// Percent
			CGFloat dividerThicknessTotal = [self dividerThickness] * ([[self subviews] count] - 1);
			CGFloat totalSize = [self isVertical] ? [self frame].size.width : [self frame].size.height;
			totalSize -= dividerThicknessTotal;
			
			return roundf((max / 100.0) * totalSize);
			break;
		}
		case 0:
		default:
		{
			// Points
			return max;
			break;
		}
	}
}

// PREFERRED PROPORTIONS AND SIZES
//
// Preferred proportions (for resizable)
// Need to store resizable subviews preferred proportions for calculating new sizes
//
// Preferred sizes (for non-resizable)
// If a non-resizable subview is ever forced larger or smaller than it prefers, we need to know it's preferred size
//
// Need to recalculate both of the above whenever a divider is moved, or a subview is added/removed or changed between resizable/non-resizable

- (void)recalculatePreferredProportionsAndSizes;
{
	NSMutableArray *stateArray = [NSMutableArray arrayWithCapacity:[[self subviews] count]];
	
	NSMutableDictionary *preferredProportions = [NSMutableDictionary dictionary];
	NSMutableDictionary *preferredSizes = [NSMutableDictionary dictionary];
	
	// Total is only the sum of resizable subviews
	CGFloat resizableTotal = 0;
	
	// Calculate resizable total
	for (NSView *subview in [self subviews])
	{
		if ([self subviewIsResizable:subview])
			resizableTotal += [self isVertical] ? [subview frame].size.width : [subview frame].size.height;
	}
	
	// Calculate resizable preferred propotions and set non-resizable preferred sizes
	for (NSView *subview in [self subviews])
	{
		int index = [[self subviews] indexOfObject:subview];
		
		if ([self subviewIsResizable:subview])
		{
			CGFloat size = [self isVertical] ? [subview frame].size.width : [subview frame].size.height;
			CGFloat proportion = (resizableTotal > 0) ? (size / resizableTotal) : 0;
			
			[preferredProportions setObject:[NSNumber numberWithFloat:proportion]
									 forKey:[NSNumber numberWithInt:index]];
			
			[stateArray addObject:[NSNumber numberWithBool:YES]];
		}
		else
		{
			CGFloat size = [self isVertical] ? [subview frame].size.width : [subview frame].size.height;
			
			[preferredSizes setObject:[NSNumber numberWithFloat:size]
							   forKey:[NSNumber numberWithInt:index]];
			
			[stateArray addObject:[NSNumber numberWithBool:NO]];
		}
	}
	
	[self setResizableSubviewPreferredProportion:preferredProportions];
	[self setNonresizableSubviewPreferredSize:preferredSizes];
	
	if (RESIZE_DEBUG_LOGS) NSLog(@"resizableSubviewPreferredProportion: %@", resizableSubviewPreferredProportion);
	if (RESIZE_DEBUG_LOGS) NSLog(@"nonresizableSubviewPreferredSize: %@", nonresizableSubviewPreferredSize);
	
	// Remember state to know when to recalculate	
	[self setStateForLastPreferredCalculations:stateArray];
	if (RESIZE_DEBUG_LOGS) NSLog(@"stateForLastPreferredCalculations: %@", stateForLastPreferredCalculations);
}

// Checks if the number or type of subviews has changed since we last recalculated
- (BOOL)validatePreferredProportionsAndSizes;
{
	if (RESIZE_DEBUG_LOGS) NSLog(@"validating preferred proportions and sizes");
	
	// Check if we even have saved proportions and sizes
	if (![self resizableSubviewPreferredProportion] || ![self nonresizableSubviewPreferredSize])
		return NO;
	
	// Check if number of items has changed
	if ([[self subviews] count] != [[self stateForLastPreferredCalculations] count])
		return NO;
	
	// Check if any of the subviews have changed between resizable and non-resizable
	for (NSView *subview in [self subviews])
	{
		int index = [[self subviews] indexOfObject:subview];
		
		if ([self subviewIsResizable:subview] != [[[self stateForLastPreferredCalculations] objectAtIndex:index] boolValue])
			return NO;
	}
	
	return YES;
}

- (void)correctCollapsiblePreferredProportionOrSize;
{
	// TODO: Assuming that the collapsible subview does not change between resizable and non-resizable while collapsed
	
	if (![self hasCollapsibleSubview])
		return;
	
	NSMutableDictionary *preferredProportions = [[self resizableSubviewPreferredProportion] mutableCopy];
	NSMutableDictionary *preferredSizes = [[self nonresizableSubviewPreferredSize] mutableCopy];
	
	NSNumber *key = [NSNumber numberWithInt:[self collapsibleSubviewIndex]];
	NSView *subview = [self collapsibleSubview];
	
	// If the collapsible subview is collapsed, we put aside its preferred propotion/size
	if ([self subviewIsCollapsed:subview])
	{
		BOOL resizable = [self subviewIsResizable:subview];
		
		if (!resizable)
		{
			NSNumber *sizeNum = [preferredSizes objectForKey:key];
			if (sizeNum)
			{
				if (RESIZE_DEBUG_LOGS) NSLog(@"removing collapsible view from preferred sizes");
				
				// TODO: Save the size for later
				
				// Remove from preferred sizes
				[preferredSizes removeObjectForKey:key];
			}
		}
		else
		{
			NSNumber *proportionNum = [preferredProportions objectForKey:key];
			if (proportionNum)
			{
				if (RESIZE_DEBUG_LOGS) NSLog(@"removing collapsible view from preferred proportions");
				
				CGFloat proportion = [proportionNum floatValue];
				
				// TODO: Save the proportion for later
				
				// Remove from preferred proportions
				[preferredProportions removeObjectForKey:key];
				
				// Recalculate other proportions
				CGFloat proportionTotal = 1.0 - proportion;
				if (proportionTotal > 0)
				{
					for (NSNumber *pkey in [preferredProportions allKeys])
					{
						CGFloat oldProportion = [[preferredProportions objectForKey:pkey] floatValue];
						CGFloat newPropotion = oldProportion / proportionTotal;
						
						[preferredProportions setObject:[NSNumber numberWithFloat:newPropotion] forKey:pkey];
					}
				}
			}
		}
		
		[self setResizableSubviewPreferredProportion:preferredProportions];
		[self setNonresizableSubviewPreferredSize:preferredSizes];
	}
	else // Otherwise, we reintegrate its preferred proportion/size
	{
		[self clearPreferredProportionsAndSizes];
		[self recalculatePreferredProportionsAndSizes];
	}
}

- (void)validateAndCalculatePreferredProportionsAndSizes;
{
	if (![self validatePreferredProportionsAndSizes])
		[self recalculatePreferredProportionsAndSizes];		
	
	// Need to make sure the collapsed subviews preferred size/proportion is in the right place
	[self correctCollapsiblePreferredProportionOrSize];
}


- (void)clearPreferredProportionsAndSizes;
{
	if (RESIZE_DEBUG_LOGS) NSLog(@"clearing preferred proportions and sizes");
	
	[self setResizableSubviewPreferredProportion:nil];
	[self setNonresizableSubviewPreferredSize:nil];
}

// RESIZING ALGORITHM

// non-resizable subviews are given preferred size
// overall remaining size is calculated
// resizable subviews are calculated based on remaining size and preferred proportions
// resizable subviews are checked for min/max constraint violations
//    if violating constraint, set to valid size and remove from resizable subviews
//    recalculate other resizable subviews and repeat
// if all resizable subviews reached constraints without meeting target size, need to resize non-resizable views
// non-resizable subviews are adjusted proportionally to meet target size
// non-resizable subviews are checked for min/max constraint violations
//    if violating constraint, set to valid size and remove from non-resizable subviews
//    recalculate other non-resizable subviews and repeat
// if all subviews reached constraints without meeting target size, need to adjust all views to fit
// proportionally resize all subviews to fit in target size, ignoring min/max constraints

- (void)resizeAndAdjustSubviews;
{
	// Temporary: for now, we will just remember the proportions the first time subviews are resized
	// we should be remember them in the user defaults so they save across quits (TODO)
	
	[self validateAndCalculatePreferredProportionsAndSizes];
	
	if (RESIZE_DEBUG_LOGS) NSLog(@"resizeSubviews begins -----------------------------------------------------");
	
	NSMutableDictionary *newSubviewSizes = [NSMutableDictionary dictionaryWithCapacity:[[self subviews] count]];
	
	// Get new total size
	CGFloat totalAvailableSize = [self isVertical] ? [self frame].size.width : [self frame].size.height;
	if (RESIZE_DEBUG_LOGS) NSLog(@"totalAvailableSize: %f", totalAvailableSize);
	
	// Calculate non-resizable subviews total
	CGFloat nonresizableSubviewsTotalPreferredSize = 0;
	for (NSNumber *size in [nonresizableSubviewPreferredSize allValues])
		nonresizableSubviewsTotalPreferredSize += [size floatValue];
	if (RESIZE_DEBUG_LOGS) NSLog(@"nonresizableSubviewsTotalPreferredSize: %f", nonresizableSubviewsTotalPreferredSize);
	
	// Calculate divider thickness total
	int dividerCount = [[self subviews] count] - 1;
	if ([self collapsibleSubviewIsCollapsed] && dividerCanCollapse) dividerCount--;
	CGFloat dividerThicknessTotal = [self dividerThickness] * dividerCount;		
	if (RESIZE_DEBUG_LOGS) NSLog(@"dividerThicknessTotal: %f", dividerThicknessTotal);
	
	// Calculate overall remaining size (could be negative)
	CGFloat resizableSubviewsTotalAvailableSize = totalAvailableSize - nonresizableSubviewsTotalPreferredSize - dividerThicknessTotal;
	if (RESIZE_DEBUG_LOGS) NSLog(@"resizableSubviewsTotalAvailableSize: %f", resizableSubviewsTotalAvailableSize);
	
	// Special case for the collapsible subview
	if ([self collapsibleSubviewIsCollapsed])
	{
		[newSubviewSizes setObject:[NSNumber numberWithFloat:0.0]
							forKey:[NSNumber numberWithInt:[self collapsibleSubviewIndex]]];
	}
	
	// Set non-resizable subviews to preferred size
	[newSubviewSizes addEntriesFromDictionary:nonresizableSubviewPreferredSize];
	
	// Set sizes of resizable views based on proportions (could be negative)
	CGFloat resizableSubviewAvailableSizeUsed = 0;
	int resizableSubviewCounter = 0;
	int resizableSubviewCount = [resizableSubviewPreferredProportion count];
	for (NSNumber *key in [resizableSubviewPreferredProportion allKeys])
	{
		resizableSubviewCounter++;
		
		CGFloat proportion = [[resizableSubviewPreferredProportion objectForKey:key] floatValue];
		CGFloat size = roundf(proportion * resizableSubviewsTotalAvailableSize);
		resizableSubviewAvailableSizeUsed += size;
		
		if (resizableSubviewCounter == resizableSubviewCount)
		{
			// Make adjustment if necessary
			size += (resizableSubviewsTotalAvailableSize - resizableSubviewAvailableSizeUsed);
		}
		
		[newSubviewSizes setObject:[NSNumber numberWithFloat:size] forKey:key];
	}
	if (RESIZE_DEBUG_LOGS) NSLog(@"newSubviewSizes after resizable proportional resizing: %@", newSubviewSizes);
	
	// TODO: Could add a special case for resizableSubviewsTotalAvailableSize <= 0 : just set all resizable subviews to minimum size 
	
	// Make array of all the resizable subviews indexes
	NSMutableArray *resizableSubviewIndexes = [[resizableSubviewPreferredProportion allKeys] mutableCopy];
	[resizableSubviewIndexes sortUsingDescriptors:[NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES] autorelease]]];
	
	// Loop until none of the resizable subviews' constraints are violated
	CGFloat proportionTotal = 1;
	CGFloat resizableSubviewsRemainingAvailableSize = resizableSubviewsTotalAvailableSize;
	int i;
	for (i = 0; i < [resizableSubviewIndexes count]; i++)
	{
		NSNumber *key = [resizableSubviewIndexes objectAtIndex:i];
		CGFloat size = [[newSubviewSizes objectForKey:key] floatValue];
		CGFloat minSize = [self subviewMinimumSize:[key intValue]];
		CGFloat maxSize = [self subviewMaximumSize:[key intValue]];
		
		BOOL overMax = size > maxSize;
		BOOL underMin = size < minSize;
		
		// Check if current item in array violates constraints
		if (underMin || overMax)
		{
			CGFloat constrainedSize = underMin ? minSize : maxSize;
			
			if (RESIZE_DEBUG_LOGS) NSLog(@"resizable subview %@ was %@, set to %f", key, (underMin ? @"under min" : @"over max"), constrainedSize);
			
			// Give subview constrained size and remove from array
			[newSubviewSizes setObject:[NSNumber numberWithFloat:constrainedSize] forKey:key];
			[resizableSubviewIndexes removeObject:key];
			
			// Adjust total proportion and remaining available size
			proportionTotal -= [[resizableSubviewPreferredProportion objectForKey:key] floatValue];
			resizableSubviewsRemainingAvailableSize -= underMin ? minSize : maxSize;
			
			// Recalculate remaining subview sizes
			CGFloat resizableSubviewRemainingSizeUsed = 0;
			int j;
			for (j = 0; j < [resizableSubviewIndexes count]; j++)
			{
				NSNumber *jKey = [resizableSubviewIndexes objectAtIndex:j];
				
				CGFloat proportion = 0;
				if (proportionTotal > 0)
					proportion = [[resizableSubviewPreferredProportion objectForKey:jKey] floatValue] / proportionTotal;
				else
					proportion = 1.0 / [resizableSubviewIndexes count];
				
				CGFloat size = roundf(proportion * resizableSubviewsRemainingAvailableSize);
				resizableSubviewRemainingSizeUsed += size;
				
				if (j == [resizableSubviewIndexes count] - 1)
				{
					// Make adjustment if necessary
					size += (resizableSubviewsRemainingAvailableSize - resizableSubviewRemainingSizeUsed);
				}
				
				[newSubviewSizes setObject:[NSNumber numberWithFloat:size] forKey:jKey];
				
				// Reset outer loop to start from beginning
				i = -1;
			}
		}
	}
	if (RESIZE_DEBUG_LOGS) NSLog(@"newSubviewSizes after resizable constraint fulfilling: %@", newSubviewSizes);		
	
	if ([resizableSubviewIndexes count] == 0 && resizableSubviewsRemainingAvailableSize != 0)
	{
		if (RESIZE_DEBUG_LOGS) NSLog(@"entering nonresizable adjustment stage");
		
		// All resizable subviews have reached constraints without reaching the target size
		
		// First try to adjust non-resizable subviews, with resizableSubviewsRemainingAvailableSize being the amount of adjustment needed
		
		// Make array of non-resizable preferred proportions (normally go by preferred sizes)
		NSMutableDictionary *nonresizableSubviewPreferredProportion = [NSMutableDictionary dictionary];
		for (NSNumber *key in [nonresizableSubviewPreferredSize allKeys])
		{
			CGFloat proportion = [[nonresizableSubviewPreferredSize objectForKey:key] floatValue] / nonresizableSubviewsTotalPreferredSize;
			
			[nonresizableSubviewPreferredProportion setObject:[NSNumber numberWithFloat:proportion] forKey:key];
		}
		
		// ResizableSubviewsRemainingAvailableSize is the amount of adjustment needed
		CGFloat nonresizableSubviewsRemainingAvailableSize = nonresizableSubviewsTotalPreferredSize + resizableSubviewsRemainingAvailableSize;
		
		// Set sizes of nonresizable views based on proportions (could be negative)
		CGFloat nonresizableSubviewAvailableSizeUsed = 0;
		int nonresizableSubviewCounter = 0;
		int nonresizableSubviewCount = [nonresizableSubviewPreferredProportion count];
		for (NSNumber *key in [nonresizableSubviewPreferredProportion allKeys])
		{
			nonresizableSubviewCounter++;
			
			CGFloat proportion = [[nonresizableSubviewPreferredProportion objectForKey:key] floatValue];
			CGFloat size = roundf(proportion * nonresizableSubviewsRemainingAvailableSize);
			nonresizableSubviewAvailableSizeUsed += size;
			
			if (nonresizableSubviewCounter == nonresizableSubviewCount)
			{
				// Make adjustment if necessary
				size += (nonresizableSubviewsRemainingAvailableSize - nonresizableSubviewAvailableSizeUsed);
			}
			
			[newSubviewSizes setObject:[NSNumber numberWithFloat:size] forKey:key];
		}
		if (RESIZE_DEBUG_LOGS) NSLog(@"newSubviewSizes after nonresizable proportional resizing: %@", newSubviewSizes);
		
		// Make array of all the non-resizable subviews indexes
		NSMutableArray *nonresizableSubviewIndexes = [[nonresizableSubviewPreferredSize allKeys] mutableCopy];
		[nonresizableSubviewIndexes sortUsingDescriptors:[NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES] autorelease]]];
		
		// Loop until none of the non-resizable subviews' constraints are violated
		CGFloat proportionTotal = 1;
		int i;
		for (i = 0; i < [nonresizableSubviewIndexes count]; i++)
		{
			NSNumber *key = [nonresizableSubviewIndexes objectAtIndex:i];
			CGFloat size = [[newSubviewSizes objectForKey:key] floatValue];
			CGFloat minSize = [self subviewMinimumSize:[key intValue]];
			CGFloat maxSize = [self subviewMaximumSize:[key intValue]];
			
			BOOL overMax = size > maxSize;
			BOOL underMin = size < minSize;
			
			// Check if current item in array violates constraints
			if (underMin || overMax)
			{
				CGFloat constrainedSize = underMin ? minSize : maxSize;
				
				if (RESIZE_DEBUG_LOGS) NSLog(@"nonresizable subview %@ was %@, set to %f", key, (underMin ? @"under min" : @"over max"), constrainedSize);
				
				// Give subview constrained size and remove from array
				[newSubviewSizes setObject:[NSNumber numberWithFloat:constrainedSize] forKey:key];
				[nonresizableSubviewIndexes removeObject:key];
				
				// Adjust total proportion and remaining available size
				proportionTotal -= [[nonresizableSubviewPreferredProportion objectForKey:key] floatValue];
				nonresizableSubviewsRemainingAvailableSize -= underMin ? minSize : maxSize;
				
				// Recalculate remaining subview sizes
				CGFloat nonresizableSubviewRemainingSizeUsed = 0;
				int j;
				for (j = 0; j < [nonresizableSubviewIndexes count]; j++)
				{
					NSNumber *jKey = [nonresizableSubviewIndexes objectAtIndex:j];
					
					CGFloat proportion = 0;
					if (proportionTotal > 0)
						proportion = [[nonresizableSubviewPreferredProportion objectForKey:jKey] floatValue] / proportionTotal;
					else
						proportion = 1.0 / [nonresizableSubviewIndexes count];
					
					CGFloat size = roundf(proportion * nonresizableSubviewsRemainingAvailableSize);
					nonresizableSubviewRemainingSizeUsed += size;
					
					if (j == [nonresizableSubviewIndexes count] - 1)
					{
						// Make adjustment if necessary
						size += (nonresizableSubviewsRemainingAvailableSize - nonresizableSubviewRemainingSizeUsed);
					}
					
					[newSubviewSizes setObject:[NSNumber numberWithFloat:size] forKey:jKey];
					
					// Reset outer loop to start from beginning
					i = -1;
				}
			}
		}
		if (RESIZE_DEBUG_LOGS) NSLog(@"newSubviewSizes after nonresizable constraint fulfilling: %@", newSubviewSizes);
		
		// If there is still overall violation, resize everything proportionally to make up the difference
		
		if ([resizableSubviewIndexes count] == 0 && nonresizableSubviewsRemainingAvailableSize != 0)
		{
			if (RESIZE_DEBUG_LOGS) NSLog(@"entering all subviews forced adjustment stage");
			
			// Calculate current proportions and use to calculate new size
			
			CGFloat allSubviewTotalCurrentSize = 0;
			for (NSNumber *size in [newSubviewSizes allValues])
				allSubviewTotalCurrentSize += [size floatValue];
			
			CGFloat allSubviewRemainingSizeUsed = 0;
			CGFloat allSubviewTotalSize = totalAvailableSize - dividerThicknessTotal;
			// TODO: What to do if even the dividers don't fit?				
			
			int k;
			for (k = 0; k < [newSubviewSizes count]; k++)
			{
				NSNumber *key = [NSNumber numberWithInt:k];
				
				CGFloat currentSize = [[newSubviewSizes objectForKey:key] floatValue];
				
				CGFloat proportion = currentSize / allSubviewTotalCurrentSize;
				CGFloat size = roundf(proportion * allSubviewTotalSize);
				allSubviewRemainingSizeUsed += size;
				
				if (k == [newSubviewSizes count] - 1)
				{
					// Make adjustment if necessary
					size += allSubviewTotalSize - allSubviewRemainingSizeUsed;
				}
				
				[newSubviewSizes setObject:[NSNumber numberWithFloat:size] forKey:key];	
			}
			if (RESIZE_DEBUG_LOGS) NSLog(@"newSubviewSizes after all subviews forced adjustment: %@", newSubviewSizes);
		}
		
		// Otherwise there is still flexibiliy in the non-resizable views, so we are done
	}
	
	// Otherwise there is still flexibility in the resizable views, so we are done
	
	// Set subview frames
	CGFloat position = 0;
	for (i = 0; i < [[self subviews] count]; i++)
	{
		NSView *subview = [[self subviews] objectAtIndex:i];
		CGFloat size = [[newSubviewSizes objectForKey:[NSNumber numberWithInt:i]] floatValue];
		
		NSRect subviewFrame = NSZeroRect;
		
		if ([self isVertical])
		{
			subviewFrame.size.height = [self frame].size.height;
			subviewFrame.size.width = size;
			subviewFrame.origin.y = [subview frame].origin.y;
			subviewFrame.origin.x = position;
		}
		else
		{
			subviewFrame.size.height = size;
			subviewFrame.size.width =  [self frame].size.width;
			subviewFrame.origin.y = position;
			subviewFrame.origin.x =  [subview frame].origin.x;
		}
		
		[subview setFrame:subviewFrame];
		
		position += size;
		
		if (dividerCanCollapse && [self subviewIsCollapsed:subview])
		{
			// Do nothing
		}
		else
		{
			position += [self dividerThickness];
		}
	}
}

- (void)splitView:(NSSplitView *)sender resizeSubviewsWithOldSize:(NSSize)oldSize
{	
	if ([secondaryDelegate isKindOfClass:[BWAnchoredButtonBar class]])
	{
		[self resizeAndAdjustSubviews];
	}
	else if ([secondaryDelegate respondsToSelector:@selector(splitView:resizeSubviewsWithOldSize:)])
	{
		[secondaryDelegate splitView:sender resizeSubviewsWithOldSize:oldSize];
	}
	else if (sender == self)
	{
		[self resizeAndAdjustSubviews];
	}
	else
	{
		[sender adjustSubviews];
	}
}

#pragma mark Force Vertical Splitters to Thin Appearance

// This class doesn't have an appearance for wide vertical splitters, so we force all vertical splitters to thin.
// We also post notifications that are used by the inspector to show & hide controls.

- (void)setDividerStyle:(NSSplitViewDividerStyle)aStyle
{
	BOOL styleChanged = NO;
	
	if (aStyle != [self dividerStyle])
		styleChanged = YES;
	
	if ([self isVertical])
		[super setDividerStyle:NSSplitViewDividerStyleThin];
	else
		[super setDividerStyle:aStyle];
	
	// There can be sizing issues during design-time if we don't call this
	[self adjustSubviews];
	
	if (styleChanged)
		[[NSNotificationCenter defaultCenter] postNotificationName:@"BWSplitViewDividerThicknessChanged" object:self];
}

- (void)setVertical:(BOOL)flag
{
	BOOL orientationChanged = NO;
	
	if (flag != [self isVertical])
		orientationChanged = YES;
		
	if (flag)
		[super setDividerStyle:NSSplitViewDividerStyleThin];
	
	[super setVertical:flag];
	
	if (orientationChanged)
		[[NSNotificationCenter defaultCenter] postNotificationName:@"BWSplitViewOrientationChanged" object:self];		
}

#pragma mark IB Inspector Support Methods

- (BOOL)checkboxIsEnabled
{
	if (![self isVertical] && [super dividerThickness] > 1.01)
		return NO;
	
	return YES;
}

- (void)setColorIsEnabled:(BOOL)flag
{
	colorIsEnabled = flag;
	
	[self setNeedsDisplay:YES];
}

- (void)setColor:(NSColor *)aColor
{
	if (color != aColor)
	{
		[color release];
		color = [aColor copy];
	}
	
	[self setNeedsDisplay:YES];
}

- (NSColor *)color
{
	if (color == nil)
		color = [[NSColor blackColor] retain];
	
    return [[color retain] autorelease]; 
}

- (NSMutableDictionary *)minValues
{
	if (minValues == nil)
		minValues = [NSMutableDictionary new];
	
    return [[minValues retain] autorelease]; 
}

- (NSMutableDictionary *)maxValues
{
	if (maxValues == nil)
		maxValues = [NSMutableDictionary new];
	
    return [[maxValues retain] autorelease]; 
}

- (NSMutableDictionary *)minUnits
{
	if (minUnits == nil)
		minUnits = [NSMutableDictionary new];
	
    return [[minUnits retain] autorelease]; 
}

- (NSMutableDictionary *)maxUnits
{
	if (maxUnits == nil)
		maxUnits = [NSMutableDictionary new];
	
    return [[maxUnits retain] autorelease]; 
}

- (void)dealloc
{
	[color release];
	[minValues release];
	[maxValues release];
	[minUnits release];
	[maxUnits release];
	[resizableSubviewPreferredProportion release];
	[nonresizableSubviewPreferredSize release];
	[toggleCollapseButton release];
	[stateForLastPreferredCalculations release];
		
	[super dealloc];
}

@end
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.