/
CCScrollLayer.m
executable file
·543 lines (433 loc) · 15 KB
/
CCScrollLayer.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
//
// CCScrollLayer.m
//
// Copyright 2010 DK101
// http://dk101.net/2010/11/30/implementing-page-scrolling-in-cocos2d/
//
// Copyright 2010 Giv Parvaneh.
// http://www.givp.org/blog/2010/12/30/scrolling-menus-in-cocos2d/
//
// Copyright 2011 Stepan Generalov
// Copyright 2011 Jeff Keeme
// Copyright 2011 Brian Feller
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "CCScrollLayer.h"
#import "Platforms/CCGL.h"
enum
{
kCCScrollLayerStateIdle,
kCCScrollLayerStateSliding,
};
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
@interface CCTouchDispatcher (targetedHandlersGetter)
- (id<NSFastEnumeration>) targetedHandlers;
@end
@implementation CCTouchDispatcher (targetedHandlersGetter)
- (id<NSFastEnumeration>) targetedHandlers
{
return targetedHandlers;
}
@end
#endif
@interface CCScrollLayer ()
- (int) pageNumberForPosition: (CGPoint) position;
@end
@implementation CCScrollLayer
@synthesize delegate = delegate_;
@synthesize minimumTouchLengthToSlide = minimumTouchLengthToSlide_;
@synthesize minimumTouchLengthToChangePage = minimumTouchLengthToChangePage_;
@synthesize marginOffset = marginOffset_;
@synthesize currentScreen = currentScreen_;
@synthesize showPagesIndicator = showPagesIndicator_;
@synthesize pagesIndicatorPosition = pagesIndicatorPosition_;
@synthesize pagesIndicatorNormalColor = pagesIndicatorNormalColor_;
@synthesize pagesIndicatorSelectedColor = pagesIndicatorSelectedColor_;
@synthesize pagesWidthOffset = pagesWidthOffset_;
@synthesize pages = layers_;
@synthesize stealTouches = stealTouches_;
@dynamic totalScreens;
- (int) totalScreens
{
return [layers_ count];
}
+(id) nodeWithLayers:(NSArray *)layers widthOffset: (int) widthOffset
{
return [[[self alloc] initWithLayers: layers widthOffset:widthOffset] autorelease];
}
-(id) initWithLayers:(NSArray *)layers widthOffset: (int) widthOffset
{
if ( (self = [super init]) )
{
NSAssert([layers count], @"CCScrollLayer#initWithLayers:widthOffset: you must provide at least one layer!");
// Enable Touches/Mouse.
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
self.touchEnabled = YES;
#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED)
self.mouseEnabled = YES;
#endif
self.stealTouches = YES;
// Set default minimum touch length to scroll.
self.minimumTouchLengthToSlide = 30.0f;
self.minimumTouchLengthToChangePage = 100.0f;
self.marginOffset = [[CCDirector sharedDirector] winSize].width;
// Show indicator by default.
self.showPagesIndicator = YES;
self.pagesIndicatorPosition = ccp(0.5f * self.contentSize.width, ceilf ( self.contentSize.height / 8.0f ));
self.pagesIndicatorNormalColor = ccc4(0x96,0x96,0x96,0xFF);
self.pagesIndicatorSelectedColor = ccc4(0xFF,0xFF,0xFF,0xFF);
// Set up the starting variables
currentScreen_ = 0;
// Save offset.
self.pagesWidthOffset = widthOffset;
// Save array of layers.
layers_ = [[NSMutableArray alloc] initWithArray:layers copyItems:NO];
[self updatePages];
}
return self;
}
- (void) dealloc
{
self.delegate = nil;
[layers_ release];
layers_ = nil;
[super dealloc];
}
- (void) updatePages
{
// Loop through the array and add the screens if needed.
int i = 0;
for (CCLayer *l in layers_)
{
l.anchorPoint = ccp(0,0);
l.contentSize = [CCDirector sharedDirector].winSize;
l.position = ccp( (i * (self.contentSize.width - self.pagesWidthOffset)), 0 );
if (!l.parent)
[self addChild:l];
i++;
}
}
#pragma mark CCLayer Methods ReImpl
- (void) visit
{
[super visit];//< Will draw after glPopScene.
if (self.showPagesIndicator)
{
int totalScreens = [layers_ count];
// Prepare Points Array
CGFloat n = (CGFloat)totalScreens; //< Total points count in CGFloat.
CGFloat pY = self.pagesIndicatorPosition.y; //< Points y-coord in parent coord sys.
CGFloat d = 16.0f; //< Distance between points.
CGPoint points[totalScreens];
for (int i=0; i < totalScreens; ++i)
{
CGFloat pX = self.pagesIndicatorPosition.x + d * ( (CGFloat)i - 0.5f*(n-1.0f) );
points[i] = ccp (pX, pY);
}
// Set GL Values
// glEnable(GL_POINT_SMOOTH);
// ccGLEnable(CC_GL_BLEND);
ccGLBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
ccPointSize( 6.0 * CC_CONTENT_SCALE_FACTOR() );
// Draw Gray Points
ccDrawColor4B(pagesIndicatorNormalColor_.r,
pagesIndicatorNormalColor_.g,
pagesIndicatorNormalColor_.b,
pagesIndicatorNormalColor_.a);
ccDrawPoints( points, totalScreens );
// Draw White Point for Selected Page
ccDrawColor4B(pagesIndicatorSelectedColor_.r,
pagesIndicatorSelectedColor_.g,
pagesIndicatorSelectedColor_.b,
pagesIndicatorSelectedColor_.a);
ccDrawPoint(points[currentScreen_]);
// Restore GL Values
ccPointSize(1.0f);
// glDisable(GL_POINT_SMOOTH);
}
}
#pragma mark Moving To / Selecting Pages
- (void) moveToPageEnded
{
if (prevScreen_ != currentScreen_)
{
if ([self.delegate respondsToSelector:@selector(scrollLayer:scrolledToPageNumber:)])
[self.delegate scrollLayer: self scrolledToPageNumber: currentScreen_];
}
prevScreen_ = currentScreen_ = [self pageNumberForPosition:self.position];
}
- (int) pageNumberForPosition: (CGPoint) position
{
CGFloat pageFloat = - self.position.x / (self.contentSize.width - self.pagesWidthOffset);
int pageNumber = ceilf(pageFloat);
if ( (CGFloat)pageNumber - pageFloat >= 0.5f)
pageNumber--;
pageNumber = MAX(0, pageNumber);
pageNumber = MIN([layers_ count] - 1, pageNumber);
return pageNumber;
}
- (CGPoint) positionForPageWithNumber: (int) pageNumber
{
return ccp( - pageNumber * (self.contentSize.width - self.pagesWidthOffset), 0.0f );
}
-(void) moveToPage:(int)page
{
if (page < 0 || page >= [layers_ count]) {
CCLOGERROR(@"CCScrollLayer#moveToPage: %d - wrong page number, out of bounds. ", page);
return;
}
id changePage = [CCMoveTo actionWithDuration:0.3 position: [self positionForPageWithNumber: page]];
changePage = [CCSequence actions: changePage,[CCCallFunc actionWithTarget:self selector:@selector(moveToPageEnded)], nil];
[self runAction:changePage];
currentScreen_ = page;
}
-(void) selectPage:(int)page
{
if (page < 0 || page >= [layers_ count]) {
CCLOGERROR(@"CCScrollLayer#selectPage: %d - wrong page number, out of bounds. ", page);
return;
}
self.position = [self positionForPageWithNumber: page];
prevScreen_ = currentScreen_;
currentScreen_ = page;
}
#pragma mark Dynamic Pages Control
- (void) addPage: (CCLayer *) aPage
{
[self addPage: aPage withNumber: [layers_ count]];
}
- (void) addPage: (CCLayer *) aPage withNumber: (int) pageNumber
{
pageNumber = MIN(pageNumber, [layers_ count]);
pageNumber = MAX(pageNumber, 0);
[layers_ insertObject: aPage atIndex: pageNumber];
[self updatePages];
[self moveToPage: currentScreen_];
}
- (void) removePage: (CCLayer *) aPage
{
[layers_ removeObject: aPage];
[self removeChild: aPage cleanup: YES];
[self updatePages];
prevScreen_ = currentScreen_;
currentScreen_ = MIN(currentScreen_, [layers_ count] - 1);
[self moveToPage: currentScreen_];
}
- (void) removePageWithNumber: (int) page
{
if (page >= 0 && page < [layers_ count])
[self removePage:[layers_ objectAtIndex: page]];
}
#pragma mark Touches
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
/** Register with more priority than CCMenu's but don't swallow touches. */
-(void) registerWithTouchDispatcher
{
CCTouchDispatcher *dispatcher = [[CCDirector sharedDirector] touchDispatcher];
[dispatcher addTargetedDelegate:self priority:kCCMenuHandlerPriority - 1 swallowsTouches:NO];
}
/** Hackish stuff - stole touches from other CCTouchDispatcher targeted delegates.
Used to claim touch without receiving ccTouchBegan. */
- (void) claimTouch: (UITouch *) aTouch
{
CCTouchDispatcher *dispatcher = [[CCDirector sharedDirector] touchDispatcher];
// Enumerate through all targeted handlers.
for ( CCTargetedTouchHandler *handler in [dispatcher targetedHandlers] )
{
// Only our handler should claim the touch.
if (handler.delegate == self)
{
if (![handler.claimedTouches containsObject: aTouch])
{
[handler.claimedTouches addObject: aTouch];
}
}
else
{
// Steal touch from other targeted delegates, if they claimed it.
if ([handler.claimedTouches containsObject: aTouch])
{
if ([handler.delegate respondsToSelector:@selector(ccTouchCancelled:withEvent:)])
{
[handler.delegate ccTouchCancelled: aTouch withEvent: nil];
}
[handler.claimedTouches removeObject: aTouch];
}
}
}
}
-(void)ccTouchCancelled:(UITouch *)touch withEvent:(UIEvent *)event
{
if( scrollTouch_ == touch ) {
scrollTouch_ = nil;
[self selectPage: currentScreen_];
}
}
-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
if( scrollTouch_ == nil ) {
scrollTouch_ = touch;
} else {
return NO;
}
CGPoint touchPoint = [touch locationInView:[touch view]];
touchPoint = [[CCDirector sharedDirector] convertToGL:touchPoint];
startSwipe_ = touchPoint.x;
state_ = kCCScrollLayerStateIdle;
return YES;
}
- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
{
if( scrollTouch_ != touch ) {
return;
}
CGPoint touchPoint = [touch locationInView:[touch view]];
touchPoint = [[CCDirector sharedDirector] convertToGL:touchPoint];
// If finger is dragged for more distance then minimum - start sliding and cancel pressed buttons.
// Of course only if we not already in sliding mode
if ( (state_ != kCCScrollLayerStateSliding)
&& (fabsf(touchPoint.x-startSwipe_) >= self.minimumTouchLengthToSlide) )
{
state_ = kCCScrollLayerStateSliding;
// Avoid jerk after state change.
startSwipe_ = touchPoint.x;
if (self.stealTouches)
{
[self claimTouch: touch];
}
if ([self.delegate respondsToSelector:@selector(scrollLayerScrollingStarted:)])
{
[self.delegate scrollLayerScrollingStarted: self];
}
}
if (state_ == kCCScrollLayerStateSliding)
{
CGFloat desiredX = (- currentScreen_ * (self.contentSize.width - self.pagesWidthOffset)) + touchPoint.x - startSwipe_;
int page = [self pageNumberForPosition:ccp(desiredX, 0)];
CGFloat offset = desiredX - [self positionForPageWithNumber:page].x;
if ((page == 0 && offset > 0) || (page == [layers_ count] - 1 && offset < 0))
offset -= marginOffset_ * offset / [[CCDirector sharedDirector] winSize].width;
else
offset = 0;
self.position = ccp(desiredX - offset, 0);
}
}
- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
{
if( scrollTouch_ != touch )
return;
scrollTouch_ = nil;
CGPoint touchPoint = [touch locationInView:[touch view]];
touchPoint = [[CCDirector sharedDirector] convertToGL:touchPoint];
int selectedPage = currentScreen_;
CGFloat delta = touchPoint.x - startSwipe_;
if (fabsf(delta) >= self.minimumTouchLengthToChangePage)
{
selectedPage = [self pageNumberForPosition:self.position];
if (selectedPage == currentScreen_)
{
if (delta < 0.f && selectedPage < [layers_ count] - 1)
selectedPage++;
else if (delta > 0.f && selectedPage > 0)
selectedPage--;
}
}
[self moveToPage:selectedPage];
}
#endif
#pragma mark Mouse
#ifdef __MAC_OS_X_VERSION_MAX_ALLOWED
- (NSInteger) mouseDelegatePriority
{
return kCCMenuHandlerPriority - 1;
}
-(BOOL) ccMouseDown:(NSEvent*)event
{
CGPoint touchPoint = [[CCDirector sharedDirector] convertEventToGL: event];
startSwipe_ = touchPoint.x;
state_ = kCCScrollLayerStateIdle;
return NO;
}
-(BOOL) ccMouseDragged:(NSEvent*)event
{
CGPoint touchPoint = [[CCDirector sharedDirector] convertEventToGL:event];
// If mouse is dragged for more distance then minimum - start sliding.
if ( (state_ != kCCScrollLayerStateSliding)
&& (fabsf(touchPoint.x-startSwipe_) >= self.minimumTouchLengthToSlide) )
{
state_ = kCCScrollLayerStateSliding;
// Avoid jerk after state change.
startSwipe_ = touchPoint.x;
if ([self.delegate respondsToSelector:@selector(scrollLayerScrollingStarted:)])
{
[self.delegate scrollLayerScrollingStarted: self];
}
}
if (state_ == kCCScrollLayerStateSliding)
{
CGFloat desiredX = (- currentScreen_ * (self.contentSize.width - self.pagesWidthOffset)) + touchPoint.x - startSwipe_;
int page = [self pageNumberForPosition:ccp(desiredX, 0)];
CGFloat offset = desiredX - [self positionForPageWithNumber:page].x;
if ((page == 0 && offset > 0) || (page == [layers_ count] - 1 && offset < 0))
offset -= marginOffset_ * offset / [[CCDirector sharedDirector] winSize].width;
else
offset = 0;
self.position = ccp(desiredX - offset, 0);
}
return NO;
}
- (BOOL)ccMouseUp:(NSEvent *)event
{
CGPoint touchPoint = [[CCDirector sharedDirector] convertEventToGL:event];
int selectedPage = currentScreen_;
CGFloat delta = touchPoint.x - startSwipe_;
if (fabsf(delta) >= self.minimumTouchLengthToChangePage)
{
selectedPage = [self pageNumberForPosition:self.position];
if (selectedPage == currentScreen_)
{
if (delta < 0.f && selectedPage < [layers_ count] - 1)
selectedPage++;
else if (delta > 0.f && selectedPage > 0)
selectedPage--;
}
}
[self moveToPage:selectedPage];
return NO;
}
- (BOOL)ccScrollWheel:(NSEvent *)theEvent
{
CGFloat deltaX = [theEvent deltaX];
CGPoint newPos = ccpAdd( self.position, ccp(deltaX, 0.0f) );
newPos.x = MIN(newPos.x, [self positionForPageWithNumber: 0].x);
newPos.x = MAX(newPos.x, [self positionForPageWithNumber: [layers_ count] - 1].x);
self.position = newPos;
prevScreen_ = currentScreen_;
currentScreen_ = [self pageNumberForPosition:self.position];
// Inform delegate about new currentScreen.
if (prevScreen_ != currentScreen_)
{
if ([self.delegate respondsToSelector:@selector(scrollLayer:scrolledToPageNumber:)])
[self.delegate scrollLayer: self scrolledToPageNumber: currentScreen_];
}
prevScreen_ = currentScreen_;
return NO;
}
#endif
@end