1 /****************************************************************************
  2  Copyright (c) 2011-2012 cocos2d-x.org
  3  Copyright (c) 2013-2014 Chukong Technologies Inc.
  4 
  5  http://www.cocos2d-x.org
  6 
  7  Permission is hereby granted, free of charge, to any person obtaining a copy
  8  of this software and associated documentation files (the "Software"), to deal
  9  in the Software without restriction, including without limitation the rights
 10  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 11  copies of the Software, and to permit persons to whom the Software is
 12  furnished to do so, subject to the following conditions:
 13 
 14  The above copyright notice and this permission notice shall be included in
 15  all copies or substantial portions of the Software.
 16 
 17  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 18  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 19  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 20  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 21  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 22  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 23  THE SOFTWARE.
 24  ****************************************************************************/
 25 
 26 /**
 27  * The PageView control of Cocos UI.
 28  * @class
 29  * @extends ccui.Layout
 30  */
 31 ccui.PageView = ccui.Layout.extend(/** @lends ccui.PageView# */{
 32     _curPageIdx: 0,
 33     _pages: null,
 34     _touchMoveDirection: null,
 35     _touchStartLocation: 0,
 36     _touchMoveStartLocation: 0,
 37     _movePagePoint: null,
 38     _leftBoundaryChild: null,
 39     _rightBoundaryChild: null,
 40     _leftBoundary: 0,
 41     _rightBoundary: 0,
 42 
 43     _isAutoScrolling: false,
 44     _autoScrollDistance: 0,
 45     _autoScrollSpeed: 0,
 46     _autoScrollDirection: 0,
 47 
 48     _childFocusCancelOffset: 0,
 49     _pageViewEventListener: null,
 50     _pageViewEventSelector: null,
 51     _className:"PageView",
 52     _eventCallback: null,
 53 
 54     /**
 55      * allocates and initializes a UIPageView.
 56      * Constructor of ccui.PageView
 57      * @example
 58      * // example
 59      * var uiPageView = new ccui.PageView();
 60      */
 61     ctor: function () {
 62         ccui.Layout.prototype.ctor.call(this);
 63         this._pages = [];
 64         this._touchMoveDirection = ccui.PageView.TOUCH_DIR_LEFT;
 65 
 66         this._movePagePoint = null;
 67         this._leftBoundaryChild = null;
 68         this._rightBoundaryChild = null;
 69 
 70         this._childFocusCancelOffset = 5;
 71         this._pageViewEventListener = null;
 72         this._pageViewEventSelector = null;
 73         this.setTouchEnabled(true);
 74     },
 75 
 76     init: function () {
 77         if (ccui.Layout.prototype.init.call(this)) {
 78             this.setClippingEnabled(true);
 79             return true;
 80         }
 81         return false;
 82     },
 83 
 84     onEnter:function(){
 85         ccui.Layout.prototype.onEnter.call(this);
 86         this.scheduleUpdate(true);
 87     },
 88 
 89     /**
 90      * Add a widget to a page of PageView.
 91      * @param {ccui.Widget} widget widget to be added to PageView.
 92      * @param {number} pageIdx index of page.
 93      * @param {Boolean} forceCreate if force create and there is no page exist, PageView would create a default page for adding widget.
 94      */
 95     addWidgetToPage: function (widget, pageIdx, forceCreate) {
 96         if (!widget || pageIdx < 0)
 97             return;
 98 
 99         var pageCount = this._getPageCount();
100         if (pageIdx < 0 || pageIdx >= pageCount) {
101             if (forceCreate) {
102                 if (pageIdx > pageCount)
103                     cc.log("pageIdx is %d, it will be added as page id [%d]", pageIdx, pageCount);
104                 var newPage = this._createPage();
105                 newPage.addChild(widget);
106                 this.addPage(newPage);
107             }
108         } else {
109             var page = this._pages[pageIdx];
110             if (page)
111                 page.addChild(widget);
112         }
113     },
114 
115     /**
116      * create page
117      * @returns {ccui.Layout}
118      * @protected
119      */
120     _createPage: function () {
121         var newPage = ccui.Layout.create();
122         newPage.setContentSize(this.getContentSize());
123         return newPage;
124     },
125 
126     /**
127      * Push back a page to PageView.
128      * @param {ccui.Layout} page
129      */
130     addPage: function (page) {
131         if (!page || this._pages.indexOf(page) != -1)
132             return;
133 
134         this.addChild(page);
135         this._pages.push(page);
136         this._doLayoutDirty = true;
137     },
138 
139     /**
140      * Insert a page to PageView.
141      * @param {ccui.Layout} page page to be added to PageView.
142      * @param {Number} idx index
143      */
144     insertPage: function (page, idx) {
145         if (idx < 0 || !page || this._pages.indexOf(page) != -1)
146             return;
147 
148         var pageCount = this._getPageCount();
149         if (idx >= pageCount)
150             this.addPage(page);
151         else {
152             this._pages[idx] = page;
153             this.addChild(page);
154         }
155         this._doLayoutDirty = true;
156     },
157 
158     /**
159      * Remove a page of PageView.
160      * @param {ccui.Layout} page
161      */
162     removePage: function (page) {
163         if (!page) {
164             return;
165         }
166         this.removeChild(page);
167         var index = this._pages.indexOf(page);
168         if(index > -1)
169             this._pages.splice(index, 1);
170         this._doLayoutDirty = true;
171     },
172 
173     /**
174      * Remove a page at index of PageView.
175      * @param {number} index
176      */
177     removePageAtIndex: function (index) {
178         if (index < 0 || index >= this._pages.length)
179             return;
180         var page = this._pages[index];
181         if (page)
182             this.removePage(page);
183     },
184 
185     /**
186      * remove all pages from PageView
187      */
188     removeAllPages: function(){
189         var locPages = this._pages;
190         for(var i = 0, len = locPages.length; i < len; i++){
191             this.removeChild(locPages[i]);
192         }
193         this._pages.length = 0;
194     },
195 
196     _updateBoundaryPages: function () {
197         var locPages = this._pages;
198         if (locPages.length <= 0) {
199             this._leftBoundaryChild = null;
200             this._rightBoundaryChild = null;
201             return;
202         }
203         this._leftBoundaryChild = locPages[0];
204         this._rightBoundaryChild = locPages[locPages.length - 1];
205     },
206 
207     _getPageCount: function(){
208         return this._pages.length;
209     },
210 
211     /**
212      * Get x position by index
213      * @param {number} idx
214      * @returns {number}
215      */
216     _getPositionXByIndex: function (idx) {
217         return (this.getContentSize().width * (idx - this._curPageIdx));
218     },
219 
220     _onSizeChanged: function () {
221         ccui.Layout.prototype._onSizeChanged.call(this);
222         this._rightBoundary = this.getContentSize().width;
223         this._doLayoutDirty = true;
224     },
225 
226     _updateAllPagesSize: function(){
227         var selfSize = this.getContentSize();
228         var locPages = this._pages;
229         for (var i = 0, len = locPages.length; i < len; i++)
230             locPages[i].setContentSize(selfSize);
231     },
232 
233     _updateAllPagesPosition: function(){
234         var pageCount = this._getPageCount();
235         if (pageCount <= 0) {
236             this._curPageIdx = 0;
237             return;
238         }
239 
240         if (this._curPageIdx >= pageCount)
241             this._curPageIdx = pageCount-1;
242 
243         var pageWidth = this.getContentSize().width;
244         var locPages = this._pages;
245         for (var i=0; i< pageCount; i++)
246             locPages[i].setPosition(cc.p((i - this._curPageIdx) * pageWidth, 0));
247     },
248 
249     /**
250      * scroll PageView to index.
251      * @param {number} idx index of page.
252      */
253     scrollToPage: function (idx) {
254         if (idx < 0 || idx >= this._pages.length)
255             return;
256         this._curPageIdx = idx;
257         var curPage = this._pages[idx];
258         this._autoScrollDistance = -(curPage.getPosition().x);
259         this._autoScrollSpeed = Math.abs(this._autoScrollDistance) / 0.2;
260         this._autoScrollDirection = this._autoScrollDistance > 0 ? ccui.PageView.DIRECTION_RIGHT : ccui.PageView.DIRECTION_LEFT;
261         this._isAutoScrolling = true;
262     },
263 
264     update: function (dt) {
265         if (this._isAutoScrolling)
266             this._autoScroll(dt);
267     },
268 
269     setLayoutType:function(type){
270 
271     },
272 
273     getLayoutType: function(){
274         return ccui.Layout.ABSOLUTE;
275     },
276 
277     _autoScroll: function(dt){
278         var step;
279         switch (this._autoScrollDirection) {
280             case ccui.PageView.DIRECTION_LEFT:
281                 step = this._autoScrollSpeed * dt;
282                 if (this._autoScrollDistance + step >= 0.0) {
283                     step = -this._autoScrollDistance;
284                     this._autoScrollDistance = 0.0;
285                     this._isAutoScrolling = false;
286                 } else
287                     this._autoScrollDistance += step;
288                 this._scrollPages(-step);
289                 if(!this._isAutoScrolling)
290                     this._pageTurningEvent();
291                 break;
292                 break;
293             case ccui.PageView.DIRECTION_RIGHT:
294                 step = this._autoScrollSpeed * dt;
295                 if (this._autoScrollDistance - step <= 0.0) {
296                     step = this._autoScrollDistance;
297                     this._autoScrollDistance = 0.0;
298                     this._isAutoScrolling = false;
299                 } else
300                     this._autoScrollDistance -= step;
301                 this._scrollPages(step);
302                 if(!this._isAutoScrolling)
303                     this._pageTurningEvent();
304                 break;
305             default:
306                 break;
307         }
308     },
309 
310     onTouchMoved: function (touch, event) {
311         this._handleMoveLogic(touch);
312         var widgetParent = this.getWidgetParent();
313         if (widgetParent)
314             widgetParent.interceptTouchEvent(ccui.Widget.TOUCH_MOVED, this, touch);
315         this._moveEvent();
316     },
317 
318     onTouchEnded: function (touch, event) {
319         ccui.Layout.prototype.onTouchEnded.call(this, touch, event);
320         this._handleReleaseLogic(touch);
321     },
322 
323     onTouchCancelled: function (touch, event) {
324         ccui.Layout.prototype.onTouchCancelled.call(this, touch, event);
325         this._handleReleaseLogic(touch);
326     },
327 
328     _doLayout: function(){
329         if (!this._doLayoutDirty)
330             return;
331 
332         this._updateAllPagesPosition();
333         this._updateAllPagesSize();
334         this._updateBoundaryPages();
335         this._doLayoutDirty = false;
336     },
337 
338     _movePages: function (offset) {
339         var arrayPages = this._pages;
340         var length = arrayPages.length;
341         for (var i = 0; i < length; i++) {
342             var child = arrayPages[i];
343             //var pos = child.getPosition();
344             //child.setPosition(pos.x + offset, pos.y);
345             child.setPositionX(child.getPositionX() + offset);
346         }
347     },
348 
349     _scrollPages: function (touchOffset) {
350         if (this._pages.length <= 0)
351             return false;
352 
353         if (!this._leftBoundaryChild || !this._rightBoundaryChild)
354             return false;
355 
356         var realOffset = touchOffset;
357         switch (this._touchMoveDirection) {
358             case ccui.PageView.TOUCH_DIR_LEFT: // left
359                 var rightBoundary = this._rightBoundaryChild.getRightBoundary();
360                 if (rightBoundary + touchOffset <= this._rightBoundary) {
361                     realOffset = this._rightBoundary - rightBoundary;
362                     this._movePages(realOffset);
363                     return false;
364                 }
365                 break;
366             case ccui.PageView.TOUCH_DIR_RIGHT: // right
367                 var leftBoundary = this._leftBoundaryChild.getLeftBoundary();
368                 if (leftBoundary + touchOffset >= this._leftBoundary) {
369                     realOffset = this._leftBoundary - leftBoundary;
370                     this._movePages(realOffset);
371                     return false;
372                 }
373                 break;
374             default:
375                 break;
376         }
377 
378         this._movePages(realOffset);
379         return true;
380     },
381 
382     _handleMoveLogic: function (touch) {
383         var offset = touch.getLocation().x - touch.getPreviousLocation().x;
384         if (offset < 0)
385             this._touchMoveDirection = ccui.PageView.TOUCH_DIR_LEFT;
386         else if (offset > 0)
387             this._touchMoveDirection = ccui.PageView.TOUCH_DIR_RIGHT;
388         this._scrollPages(offset);
389     },
390 
391     _handleReleaseLogic: function (touchPoint) {
392         if (this._pages.length <= 0)
393             return;
394         var curPage = this._pages[this._curPageIdx];
395         if (curPage) {
396             var curPagePos = curPage.getPosition();
397             var pageCount = this._pages.length;
398             var curPageLocation = curPagePos.x;
399             var pageWidth = this.getSize().width;
400             var boundary = pageWidth / 2.0;
401             if (curPageLocation <= -boundary) {
402                 if (this._curPageIdx >= pageCount - 1)
403                     this._scrollPages(-curPageLocation);
404                 else
405                     this.scrollToPage(this._curPageIdx + 1);
406             }
407             else if (curPageLocation >= boundary) {
408                 if (this._curPageIdx <= 0)
409                     this._scrollPages(-curPageLocation);
410                 else
411                     this.scrollToPage(this._curPageIdx - 1);
412             } else
413                 this.scrollToPage(this._curPageIdx);
414         }
415     },
416 
417     interceptTouchEvent: function (handleState, sender, touch) {
418         var touchPoint = touch.getLocation();
419         switch (handleState) {
420             case ccui.Widget.TOUCH_BEGAN:
421                 break;
422             case ccui.Widget.TOUCH_MOVED:
423                 var offset = 0;
424                 offset = Math.abs(sender.getTouchBeganPosition().x - touchPoint.x);
425                 if (offset > this._childFocusCancelOffset) {
426                     sender.setFocused(false);
427                     this._handleMoveLogic(touch);
428                 }
429                 break;
430             case ccui.Widget.TOUCH_ENDED:
431             case ccui.Widget.TOUCH_CANCELED:
432                 this._handleReleaseLogic(touch);
433                 break;
434         }
435     },
436 
437     _pageTurningEvent: function () {
438         if (this._pageViewEventListener && this._pageViewEventSelector)
439             this._pageViewEventSelector.call(this._pageViewEventListener, this, ccui.PageView.EVENT_TURNING);
440         if (this._eventCallback)
441             this._eventCallback(this, ccui.PageView.EVENT_TURNING);
442     },
443 
444     /**
445      * @param {Function} selector
446      * @param {Object} target
447      */
448     addEventListenerPageView: function (selector, target) {
449         this._pageViewEventSelector = selector;
450         this._pageViewEventListener = target;
451     },
452 
453     addEventListener: function(callback){
454         this._eventCallback = callback;
455     },
456 
457     /**
458      * get current page index
459      * @returns {number}
460      */
461     getCurPageIndex: function () {
462         return this._curPageIdx;
463     },
464 
465     /**
466      * get all pages of PageView
467      * @returns {Array}
468      */
469     getPages:function(){
470         return this._pages;
471     },
472 
473     /**
474      * get a page from PageView by index
475      * @param {Number} index
476      * @returns {ccui.Layout}
477      */
478     getPage: function(index){
479         if (index < 0 || index >= this.getPages().size())
480             return null;
481         return this._pages[index];
482     },
483 
484     /**
485      * Returns the "class name" of widget.
486      * @returns {string}
487      */
488     getDescription: function () {
489         return "PageView";
490     },
491 
492     _createCloneInstance: function () {
493         return ccui.PageView.create();
494     },
495 
496     _copyClonedWidgetChildren: function (model) {
497         var arrayPages = model.getPages();
498         for (var i = 0; i < arrayPages.length; i++) {
499             var page = arrayPages[i];
500             this.addPage(page.clone());
501         }
502     },
503 
504     _copySpecialProperties: function (pageView) {
505         ccui.Layout.prototype._copySpecialProperties.call(this, pageView);
506         this._eventCallback = pageView._eventCallback;
507         this._pageViewEventListener = pageView._pageViewEventListener;
508         this._pageViewEventSelector = pageView._pageViewEventSelector;
509     }
510 });
511 /**
512  * allocates and initializes a UIPageView.
513  * @deprecated
514  * @return {ccui.PageView}
515  * @example
516  * // example
517  * var uiPageView = ccui.PageView.create();
518  */
519 ccui.PageView.create = function () {
520     return new ccui.PageView();
521 };
522 
523 // Constants
524 //PageView event
525 ccui.PageView.EVENT_TURNING = 0;
526 
527 //PageView touch direction
528 ccui.PageView.TOUCH_DIR_LEFT = 0;
529 ccui.PageView.TOUCH_DIR_RIGHT = 1;
530 
531 //PageView auto scroll direction
532 ccui.PageView.DIRECTION_LEFT = 0;
533 ccui.PageView.DIRECTION_RIGHT = 1;
534