-
Notifications
You must be signed in to change notification settings - Fork 1
/
UKDistributedView.m
3258 lines (2563 loc) · 101 KB
/
UKDistributedView.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
//
// UKDistributedView.m
// UKDistributedView
//
// Created by Uli Kusterer on 2003-06-24.
// Copyright (c) 2003 M. Uli Kusterer. All rights reserved.
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
/* -----------------------------------------------------------------------------
Headers:
-------------------------------------------------------------------------- */
#import "UKDistributedView.h"
#import <limits.h>
#import <QuartzCore/QuartzCore.h>
/* -----------------------------------------------------------------------------
Notifications:
-------------------------------------------------------------------------- */
NSString* UKDistributedViewSelectionDidChangeNotification = @"UKDistributedViewSelectionDidChange";
/* -----------------------------------------------------------------------------
Private Methods:
-------------------------------------------------------------------------- */
@interface UKDistributedView ()
-(NSRect) snapRectToGrid: (NSRect)box; // Calls forceRectToGrid if forceToGrid is true, otherwise returns the rect unmodified.
-(NSRect) forceRectToGrid: (NSRect)box;
-(NSRect) flipRectsYAxis: (NSRect)box;
-(void) contentSizeChanged;
-(void) drawGridForDrawRect: (NSRect)rect;
-(void) drawCellsForDrawRect: (NSRect)rect;
-(void) drawSelectionRectForDrawRect: (NSRect)rect;
-(void) drawDropHiliteForDrawRect: (NSRect)rect;
-(void) selectionSetNeedsDisplay;
-(void) invalidateVisibleItemsCache;
-(void) extendCacheByVisibleItemIndexesInRect: (NSRect)inBox startingAtIndex: (NSUInteger)startIdx; // Build cache of (potentially) visible items used for drawing and mouse tracking.
-(NSUInteger) getItemIndexForSuggestionInRect: (NSRect)aBox; // Uses cache in multi-positioning mode, otherwise calls getUncachedItemIndexInRect:.
-(NSUInteger) getUncachedItemIndexInRect: (NSRect)aBox;
-(void) removeAllRowsFromSuggestionCacheBelow: (float)yPos;
-(NSRect) rectAroundItems: (NSArray*)dragIndexes;
-(void) initiateDrag: (NSEvent*)event;
-(void) initiateMove;
-(void) addPositionsOfItems: (NSArray*)indexes toPasteboard: (NSPasteboard*)pboard;
-(NSMutableArray*) positionsOfItemsOnPasteboard: (NSPasteboard*)pboard forImagePosition: (NSPoint)imgPos;
-(IBAction) cellClicked: (id)sender;
-(NSRect) computeFrame;
@end
/* -----------------------------------------------------------------------------
UKDistributedView:
-------------------------------------------------------------------------- */
@implementation UKDistributedView
-(id) initWithFrame: (NSRect)frame
{
self = [super initWithFrame:frame];
if( self )
{
lastPos = NSMakePoint(0,0);
cellSize = NSMakeSize( 100.0,100.0 );
gridSize.width = cellSize.width /2;
gridSize.height = cellSize.height /2;
contentInset = 8.0;
flags.bits.forceToGrid = flags.bits.snapToGrid = NO;
prototype = [[NSCell alloc] init];
mouseItem = NSNotFound;
dragDestItem = NSNotFound;
flags.bits.dragMovesItems = NO;
delegate = dataSource = nil;
selectionSet = [[NSMutableSet alloc] init];
flags.bits.useSelectionRect = flags.bits.allowsMultipleSelection = flags.bits.allowsEmptySelection = YES;
flags.bits.sizeToFit = YES;
flags.bits.showSnapGuides = YES;
runtimeFlags.bits.drawSnappedRects = NO;
flags.bits.drawsGrid = NO;
flags.bits.drawsBackground = NO;
gridColor = [[NSColor gridColor] retain];
selectionRect = NSZeroRect;
visibleItemRect = NSZeroRect;
visibleItems = [[NSMutableArray alloc] init];
editedItem = NSNotFound;
}
return self;
}
-(id) init
{
// always route through designated initializer
return [self initWithFrame:NSZeroRect];
}
/* -----------------------------------------------------------------------------
initWithCoder:
Persistence constructor needed for IB palette.
REVISIONS:
2004-12-02 UK Changed to use flags structure instead of lots of BOOLs.
2004-12-01 UK Documented.
-------------------------------------------------------------------------- */
-(id) initWithCoder:(NSCoder *)decoder
{
self = [super initWithCoder:decoder];
lastPos = NSMakePoint(0,0);
mouseItem = NSNotFound;
dragDestItem = NSNotFound;
delegate = dataSource = nil;
selectionRect = NSZeroRect;
visibleItemRect = NSZeroRect;
visibleItems = [[NSMutableArray alloc] init];
editedItem = NSNotFound;
if( [decoder allowsKeyedCoding] )
{
NSUInteger len = sizeof(NSSize);
cellSize = *(NSSize*)[decoder decodeBytesForKey: @"UKDVcellSize" returnedLength: &len];
gridSize = *(NSSize*)[decoder decodeBytesForKey: @"UKDVgridSize" returnedLength: &len];
contentInset = [decoder decodeFloatForKey: @"UKDVcontentInset"];
flags.allFlags = [decoder decodeIntForKey: @"UKDVflags"];
prototype = [[decoder decodeObjectForKey: @"UKDVprototype"] retain];
gridColor = [[decoder decodeObjectForKey: @"UKDVgridColor"] retain];
}
else
{
[decoder decodeValueOfObjCType:@encode(NSSize) at: &cellSize];
[decoder decodeValueOfObjCType:@encode(NSSize) at: &gridSize];
[decoder decodeValueOfObjCType:@encode(float) at: &contentInset];
[decoder decodeValueOfObjCType:@encode(int) at: &flags.allFlags];
prototype = [[decoder decodeObject] retain];
gridColor = [[decoder decodeObject] retain];
}
// Apply defaults, if needed:
if( !prototype )
prototype = [[NSCell alloc] init];
selectionSet = [[NSMutableSet set] retain];
if( !gridColor )
gridColor = [[NSColor gridColor] retain];
return self;
}
/* -----------------------------------------------------------------------------
encodeWithCoder:
Save this view to a file. Used by IB.
REVISIONS:
2004-12-02 UK Changed to use flags structure instead of lots of BOOLs.
2004-12-01 UK Documented.
-------------------------------------------------------------------------- */
-(void) encodeWithCoder:(NSCoder *)coder
{
[super encodeWithCoder:coder];
if( [coder allowsKeyedCoding] )
{
[coder encodeBytes: (const uint8_t *)&cellSize length: sizeof(NSSize) forKey: @"UKDVcellSize"];
[coder encodeBytes: (const uint8_t *)&gridSize length: sizeof(NSSize) forKey: @"UKDVgridSize"];
[coder encodeFloat: contentInset forKey: @"UKDVcontentInset"];
[coder encodeInt: flags.allFlags forKey: @"UKDVflags"];
[coder encodeObject: prototype forKey: @"UKDVprototype"];
[coder encodeObject: gridColor forKey: @"UKDVgridColor"];
}
else
{
[coder encodeValueOfObjCType:@encode(NSSize) at: &cellSize];
[coder encodeValueOfObjCType:@encode(NSSize) at: &gridSize];
[coder encodeValueOfObjCType:@encode(float) at: &contentInset];
[coder encodeValueOfObjCType:@encode(int) at: &flags.allFlags];
[coder encodeObject: prototype];
[coder encodeObject: gridColor];
}
}
-(void) dealloc
{
[visibleItems release];
[selectionSet release];
[prototype release];
[super dealloc];
}
// -----------------------------------------------------------------------------
// Selection Management:
// -----------------------------------------------------------------------------
#pragma mark Selection Management
-(NSUInteger) selectedItem
{
return [self selectedItemIndex];
}
-(NSUInteger) selectedItemIndex
{
NSEnumerator* enny = [selectionSet objectEnumerator];
NSUInteger i = NSNotFound;
NSNumber* num;
if( (num = [enny nextObject]) )
i = [num unsignedIntegerValue];
return i;
}
-(NSEnumerator*) selectedItemEnumerator
{
return [selectionSet objectEnumerator];
}
-(NSUInteger) selectedItemCount
{
return [selectionSet count];
}
-(void) selectItem: (NSUInteger)index byExtendingSelection: (BOOL)ext
{
NSParameterAssert( index != NSNotFound && index < [[self dataSource] numberOfItemsInDistributedView: self] );
if (![self allowsMultipleSelection])
ext = NO;
if( !ext )
{
[self selectionSetNeedsDisplay];
[selectionSet removeAllObjects];
}
if( index != NSNotFound && ![selectionSet containsObject:[NSNumber numberWithInteger: index]] )
[selectionSet addObject:[NSNumber numberWithInteger: index]];
[self itemNeedsDisplay: index];
}
-(void) deselectItem: (NSUInteger)index
{
[selectionSet removeObject: [NSNumber numberWithInteger: index]];
[[NSNotificationCenter defaultCenter] postNotificationName: UKDistributedViewSelectionDidChangeNotification
object: self];
[self itemNeedsDisplay: index];
}
-(void) selectItemsInRect: (NSRect)aBox byExtendingSelection: (BOOL)ext
{
if (![self allowsMultipleSelection])
return;
NSUInteger x, count = [[self dataSource] numberOfItemsInDistributedView:self];
if( !ext )
{
[self selectionSetNeedsDisplay]; // Make sure items are redrawn unselected.
[selectionSet removeAllObjects];
}
aBox = [self flipRectsYAxis: aBox];
for( x = 0; x < count; x++ )
{
NSRect box = [self rectForItemAtIndex:x];
box = [self snapRectToGrid: box];
if( NSIntersectsRect( aBox, box ) )
{
if( ![selectionSet containsObject:[NSNumber numberWithInteger: x]] )
[selectionSet addObject:[NSNumber numberWithInteger: x]];
if( [delegate respondsToSelector: @selector(distributedView:didSelectItemIndex:)] )
[delegate distributedView:self didSelectItemIndex: x];
}
}
[self selectionSetNeedsDisplay]; // Make sure newly selected items are drawn that way.
[[NSNotificationCenter defaultCenter] postNotificationName: UKDistributedViewSelectionDidChangeNotification
object: self];
}
-(void) selectItemContainingString: (NSString*)str
{
NSUInteger matchItem = [delegate distributedView:self itemIndexForString: str options: NSCaseInsensitiveSearch];
if( matchItem != NSNotFound )
{
[self selectItem: matchItem byExtendingSelection: NO];
[self scrollItemToVisible: matchItem];
}
}
-(void) updateSelectionSet
{
NSEnumerator* selEnny = [selectionSet objectEnumerator];
NSUInteger count = [[self dataSource] numberOfItemsInDistributedView:self];
NSNumber* currIndex = nil;
while( (currIndex = [selEnny nextObject]) )
{
if( [currIndex unsignedIntegerValue] >= count )
[selectionSet removeObject: currIndex];
}
}
// -----------------------------------------------------------------------------
// Menu actions:
// -----------------------------------------------------------------------------
#pragma mark Menu Actions
-(IBAction) selectAll: (id)sender
{
NSUInteger count = [[self dataSource] numberOfItemsInDistributedView:self];
[selectionSet removeAllObjects];
while( count > 0 )
{
if( [delegate respondsToSelector: @selector(distributedView:didSelectItemIndex:)] )
[delegate distributedView:self didSelectItemIndex: count];
[selectionSet addObject:[NSNumber numberWithInteger: count]];
if( count == 0 )
break;
}
[self setNeedsDisplay:YES];
[[NSNotificationCenter defaultCenter] postNotificationName: UKDistributedViewSelectionDidChangeNotification
object: self];
}
-(IBAction) deselectAll: (id)sender
{
if( flags.bits.allowsEmptySelection )
{
NSSet* oldSelection = [[selectionSet copy] autorelease];
[selectionSet removeAllObjects];
[self itemSetNeedsDisplay: oldSelection];
[[NSNotificationCenter defaultCenter] postNotificationName: UKDistributedViewSelectionDidChangeNotification
object: self];
}
}
-(IBAction) toggleDrawsGrid: (id)sender
{
[self setDrawsGrid: !flags.bits.drawsGrid];
}
-(IBAction) toggleSnapToGrid: (id)sender
{
[self setSnapToGrid: !flags.bits.snapToGrid];
}
/* -----------------------------------------------------------------------------
validateMenuItem:
Make sure menu items are enabled properly.
REVISIONS:
2003-06-29 UK Created.
-------------------------------------------------------------------------- */
-(BOOL) validateMenuItem: (NSMenuItem*)menuItem
{
// Edit menu commands:
if( [menuItem action] == @selector(selectAll:) )
return flags.bits.allowsMultipleSelection;
else if( [menuItem action] == @selector(deselectAll:) )
return( ([self selectedItemCount] > 0) && flags.bits.allowsEmptySelection );
// Grid, repositioning and other Finder-like behaviour:
else if( [menuItem action] == @selector(positionAllItems:) )
return [[self dataSource] respondsToSelector: @selector(distributedView:setPosition:forItemIndex:)];
else if( [menuItem action] == @selector(snapAllItemsToGrid:) )
return [[self dataSource] respondsToSelector: @selector(distributedView:setPosition:forItemIndex:)];
else if( [menuItem action] == @selector(toggleDrawsGrid:) )
{
[menuItem setState: flags.bits.drawsGrid];
return YES;
}
else if( [menuItem action] == @selector(toggleSnapToGrid:) )
{
[menuItem setState: flags.bits.snapToGrid];
return YES;
}
else if( [menuItem action] == @selector(rescrollItems:) ) // Don't see why you'd want a menu item for this (besides debugging). You should really call this from your window zooming code.
return YES;
else if( [delegate respondsToSelector: [menuItem action]] )
{
if( [delegate respondsToSelector: @selector(validateMenuItem:)] )
return [delegate validateMenuItem: menuItem];
else
return YES;
}
else
return [self respondsToSelector: [menuItem action]];
}
// -----------------------------------------------------------------------------
// Accessors:
// -----------------------------------------------------------------------------
#pragma mark Accessors
/* Set this to NO if you never want more than one item to be selected: */
-(void) setAllowsMultipleSelection: (BOOL)state
{
flags.bits.allowsMultipleSelection = state;
if( !state && [selectionSet count] > 1 )
{
[self selectionSetNeedsDisplay]; // Make sure all unselected items are redrawn.
[selectionSet autorelease];
selectionSet = [[NSMutableSet setWithObject: [selectionSet anyObject]] retain];
}
}
-(BOOL) allowsMultipleSelection
{
return flags.bits.allowsMultipleSelection;
}
/* Set this to NO if you always want at least one item to be selected: */
-(void) setAllowsEmptySelection: (BOOL)state
{
flags.bits.allowsEmptySelection = state;
if( !state && [selectionSet count] == 0 )
{
[selectionSet addObject:[NSNumber numberWithInteger: 0]];
[self itemNeedsDisplay: 0];
}
}
-(BOOL) allowsEmptySelection
{
return flags.bits.allowsEmptySelection;
}
/* If you want the user to be able to click in the view's background to drag
a "rubber-band" selection rectangle for selecting multiple items, set this
to YES: */
-(void) setUseSelectionRect: (BOOL)state
{
flags.bits.useSelectionRect = state;
// Selection rect implicitly turns on allowsMultipleSelection:
if( (!flags.bits.allowsMultipleSelection) && state )
[self setAllowsMultipleSelection:YES];
if( (!flags.bits.allowsEmptySelection) && state )
[self setAllowsEmptySelection:YES];
}
-(BOOL) useSelectionRect
{
return flags.bits.useSelectionRect && flags.bits.allowsMultipleSelection && flags.bits.allowsEmptySelection;
}
/* If drawsGrid == YES, this color will be used to draw grid lines: */
-(void) setGridColor: (NSColor*)c
{
[c retain];
[gridColor release];
gridColor = c;
}
-(NSColor*) gridColor
{
return gridColor;
}
/* The prototype is the "data cell" used for displaying items:
Use this to change the cell type used for display. */
-(void) setPrototype: (NSCell*)aCell
{
[aCell retain];
[prototype autorelease];
prototype = aCell;
NS_DURING
[prototype setTarget: self];
[prototype setAction: @selector(cellClicked:)];
NS_HANDLER
// NSImageCell throws on setTarget/setAction :-T
NS_ENDHANDLER
}
-(id) prototype
{
return prototype;
}
/* All items's positions will be nudged to lie on a grid coordinate:
This will only modify the coordinates during display. This will
*not* change any actual item positions, and this doesn't make sure
that no items overlap. */
-(void) setForceToGrid: (BOOL)state
{
flags.bits.forceToGrid = state;
[self setNeedsDisplay: YES];
}
-(BOOL) forceToGrid
{
return flags.bits.forceToGrid;
}
/* Dragging an item moves the items or starts drag and drop. If you're just
after NSTableView-ish behavior, you'll want this to be NO. */
-(void) setDragMovesItems: (BOOL)state
{
flags.bits.dragMovesItems = state;
}
-(BOOL) dragMovesItems
{
return flags.bits.dragMovesItems;
}
/* When dragMovesItems == YES and the data source doesn't implement DnD, drags
happen locally and 'live' within the view, and simply reposition the items.
If you set dragLocally to YES, local drags will also be used when the data
source implements DnD, and "real" DnD will not happen until the mouse leaves
the view's visible rectangle. */
-(void) setDragLocally: (BOOL)state
{
flags.bits.dragLocally = state;
}
-(BOOL) dragLocally
{
return flags.bits.dragLocally;
}
/* Whenever an object moves, make this view resize to fit. */
-(void) setSizeToFit: (BOOL)state
{
flags.bits.sizeToFit = state;
}
-(BOOL) sizeToFit
{
return flags.bits.sizeToFit;
}
/* If you need to positionItem: or suggestedPosition a number of items in a row,
call this around these calls. That way, the view will keep track of the
previous item's position and start looking for a position for the next
one after that, instead of starting at the top again. */
-(void) setMultiPositioningMode: (BOOL)state
{
if( state )
{
lastSuggestedItemPos = NSMakePoint(0,0);
NSUInteger count = [[self dataSource] numberOfItemsInDistributedView: self];
[itemsBelowLastSuggested release];
itemsBelowLastSuggested = [[NSMutableArray alloc] initWithCapacity: count];
NSUInteger x;
for( x = 0; x < count; x++ )
[itemsBelowLastSuggested addObject: [NSNumber numberWithInteger: x]];
}
else
{
[itemsBelowLastSuggested release];
itemsBelowLastSuggested = nil;
}
runtimeFlags.bits.multiPositioningMode = state;
}
-(BOOL) multiPositioningMode
{
return runtimeFlags.bits.multiPositioningMode;
}
/* Always force newly positioned and moved items to lie on the grid. */
-(void) setSnapToGrid: (BOOL)state
{
flags.bits.snapToGrid = state;
}
-(BOOL) snapToGrid
{
return flags.bits.snapToGrid;
}
-(void) setShowSnapGuides: (BOOL)state
{
flags.bits.showSnapGuides = state;
}
-(BOOL) showSnapGuides
{
return flags.bits.showSnapGuides;
}
-(void) setDrawsGrid: (BOOL)state
{
flags.bits.drawsGrid = state;
[self setNeedsDisplay: YES];
}
-(BOOL) drawsGrid
{
return flags.bits.drawsGrid;
}
// The number of pixels of border to keep around the items:
-(void) setContentInset: (float)inset
{
contentInset = inset;
if( flags.bits.forceToGrid )
[self setNeedsDisplay: YES];
}
-(float) contentInset
{
return contentInset;
}
// The cell size to use for our items:
-(void) setCellSize: (NSSize)size
{
cellSize = size;
gridSize.width = cellSize.width /2;
gridSize.height = cellSize.height /2;
if( flags.bits.forceToGrid )
[self setNeedsDisplay: YES];
}
-(NSSize) cellSize
{
return cellSize;
}
// The size to use for our positioning grid:
-(void) setGridSize: (NSSize)size
{
gridSize = size;
if( flags.bits.forceToGrid )
[self setNeedsDisplay: YES];
}
-(NSSize) gridSize
{
return gridSize;
}
-(id) dataSource
{
return dataSource;
}
-(void) setDataSource: (id)d
{
dataSource = d;
}
-(id) delegate
{
return delegate;
}
-(void) setDelegate: (id)d
{
delegate = d;
}
-(void) setDrawsBackground: (BOOL)drawIt
{
flags.bits.drawsBackground = drawIt;
[self setNeedsDisplay: YES];
}
-(BOOL) drawsBackground
{
return flags.bits.drawsBackground;
}
// -----------------------------------------------------------------------------
// Item Positioning:
// -----------------------------------------------------------------------------
#pragma mark Item Positioning
/* Position all items in order on the grid:
This changes all items' positions *permanently*. Note that this simply tries to
fit the items as orderly rows in the given rect, wrapping at the right edge. */
-(IBAction) positionAllItems: (id)sender
{
if( ![[self dataSource] respondsToSelector: @selector(distributedView:setPosition:forItemIndex:)] )
return;
BOOL layerBased = [self.dataSource respondsToSelector: @selector(distributedView:titleAtItemIndex:)];
NSRect myFrame = [self frame];
NSUInteger numCols,
x,
col = 0,
row = 0,
count = [[self dataSource] numberOfItemsInDistributedView:self];
// Calculate display rect:
myFrame.origin.x += contentInset;
myFrame.origin.y += contentInset;
myFrame.size.width -= contentInset *2;
myFrame.size.height -= contentInset *2;
// Calculate # of items that fit in display area in an orderly fashion:
numCols = truncf(myFrame.size.width / cellSize.width);
// Now loop over all slots in the window where we would put something:
for( x = 0; x < count; x++ )
{
if( col >= numCols )
{
col = 0;
row++;
}
NSRect testBox = NSMakeRect( (col * cellSize.width) +contentInset,
(row * cellSize.height) +contentInset,
cellSize.width, cellSize.height );
[[self dataSource] distributedView:self setPosition:testBox.origin forItemIndex:x];
col++;
}
[[self window] invalidateCursorRectsForView:self];
[self contentSizeChanged];
if( layerBased )
[self reloadData];
else
[self setNeedsDisplay:YES];
}
/* Position all items on the closest grid location to their current location:
This changes all items' positions *permanently*. */
-(IBAction) snapAllItemsToGrid: (id)sender
{
if( ![[self dataSource] respondsToSelector: @selector(distributedView:setPosition:forItemIndex:)] )
return;
BOOL layerBased = [self.dataSource respondsToSelector: @selector(distributedView:titleAtItemIndex:)];
NSUInteger x,
count = [[self dataSource] numberOfItemsInDistributedView:self];
// Now loop over all slots in the window where we would put something:
for( x = 0; x < count; x++ )
{
NSRect testBox = [self rectForItemAtIndex:x];
testBox = [self forceRectToGrid:testBox];
[[self dataSource] distributedView:self setPosition:testBox.origin forItemIndex:x];
if( layerBased )
[self itemNeedsDisplay: x];
}
[[self window] invalidateCursorRectsForView:self];
[self contentSizeChanged];
[self setNeedsDisplay:YES];
}
/* -----------------------------------------------------------------------------
suggestedPosition:
Reposition the item at the specified index. This moves the item
somewhere where there is no other item.
Note that this will *always* move the current item.
REVISIONS:
2004-12-02 UK Added NSParameterAssert call.
-------------------------------------------------------------------------- */
-(void) positionItem: (NSUInteger)itemIndex
{
NSParameterAssert( itemIndex != NSNotFound && itemIndex < [[self dataSource] numberOfItemsInDistributedView: self] );
NSRect myFrame = [self frame];
NSUInteger numCols, numRows,
col, row;
// Calculate display rect:
myFrame.origin.x += contentInset;
myFrame.origin.y += contentInset;
myFrame.size.width -= contentInset *2;
myFrame.size.height -= contentInset *2;
// Calculate # of grid locations where we can put items:
numCols = myFrame.size.width / gridSize.width;
//numRows = myFrame.size.height / gridSize.height;
numRows = INT_MAX;
NSUInteger startRow = 0, startCol = 0;
if( runtimeFlags.bits.multiPositioningMode )
startRow = lastSuggestedItemPos.y;
if( runtimeFlags.bits.multiPositioningMode )
startCol = lastSuggestedItemPos.x;
// Now loop over all slots in the window where we would put something:
for( row = startRow; row < numRows; row++ )
{
for( col = startCol; col < numCols; col++ )
{
NSRect testBox = NSMakeRect( (col * gridSize.width) +contentInset,
(row * cellSize.height) +contentInset,
cellSize.width, cellSize.height );
NSUInteger foundIndex = [self getUncachedItemIndexInRect:testBox];
if( foundIndex == NSNotFound ) // No item in this rect?
{
[[self dataSource] distributedView:self setPosition:testBox.origin forItemIndex:itemIndex];
lastSuggestedItemPos.x = col;
lastSuggestedItemPos.y = row;
[[self window] invalidateCursorRectsForView:self];
return;
}
}
startCol = 0; // Only first time round do we want to start in that row.
}
}
/* -----------------------------------------------------------------------------
suggestedPosition:
Returns a position that is suggested for a new item. This doesn't
propose any positions at which there already are items.
REVISIONS:
2004-12-02 UK Documented.
-------------------------------------------------------------------------- */
-(NSPoint) suggestedPosition
{
NSRect myFrame = [self frame];
NSUInteger numCols, numRows,
col, row, startRow = 0, startCol = 0;
// Calculate display rect:
myFrame.origin.x += contentInset;
myFrame.origin.y += contentInset;
myFrame.size.width -= contentInset *2;
myFrame.size.height -= contentInset *2;
// Calculate # of grid slots where we could put this item:
numCols = myFrame.size.width / gridSize.width;
numRows = myFrame.size.height / gridSize.height;
if( runtimeFlags.bits.multiPositioningMode )
startRow = lastSuggestedItemPos.y;
if( runtimeFlags.bits.multiPositioningMode )
startCol = lastSuggestedItemPos.x;
// Now loop over all slots in the window where we would put something:
for( row = startRow; row < (startRow +(numRows *10)); row++ ) // * 10 so we don't try infinitely. Add to startRow since otherwise long lists would start stacking too early.
{
for( col = startCol; col < numCols; col++ )
{
NSRect testBox = NSMakeRect( (col * gridSize.width) +contentInset,
(row * gridSize.height) +contentInset,
cellSize.width, cellSize.height );
if( [self getItemIndexForSuggestionInRect: testBox] == NSNotFound ) // No item in this rect?
{
if( runtimeFlags.bits.multiPositioningMode && row > lastSuggestedItemPos.y )
[self removeAllRowsFromSuggestionCacheBelow: testBox.origin.y];
[itemsBelowLastSuggested addObject: [NSNumber numberWithInteger: [[self dataSource] numberOfItemsInDistributedView: self]]];
lastSuggestedItemPos.x = col;
lastSuggestedItemPos.y = row;
return testBox.origin;
}
}
startCol = 0;
}
return NSMakePoint(contentInset,contentInset);
}
/* -----------------------------------------------------------------------------
itemPositionBasedOnItemIndex:
Calculate a position for an item based on the item's index. Call this
from your data source if you want items to "wrap" to the width of the
view, like the Finder's "keep arranged by XX" option.
REVISIONS:
2004-12-02 UK Added NSParameterAssert call.
-------------------------------------------------------------------------- */
-(NSPoint) itemPositionBasedOnItemIndex: (NSUInteger)row
{
NSPoint pos = { 0, 0 };
NSUInteger numCols = truncf(([self frame].size.width -(contentInset *2)) / cellSize.width);
if( numCols < 1 )
numCols = 1;
pos.x = contentInset +(row % numCols) * cellSize.width;
pos.y = contentInset +truncf( row / numCols ) * cellSize.height;
return pos;
}
/* -----------------------------------------------------------------------------
rectAroundItems:
Return a rectangle enclosing all the items whose indexes are specified
in the NSNumbers in the array dragIndexes.
REVISIONS:
2003-12-20 UK Created.
-------------------------------------------------------------------------- */