CCMenu.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. /****************************************************************************
  2. Copyright (c) 2008-2010 Ricardo Quesada
  3. Copyright (c) 2011-2012 cocos2d-x.org
  4. Copyright (c) 2013-2014 Chukong Technologies Inc.
  5. http://www.cocos2d-x.org
  6. Permission is hereby granted, free of charge, to any person obtaining a copy
  7. of this software and associated documentation files (the "Software"), to deal
  8. in the Software without restriction, including without limitation the rights
  9. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. copies of the Software, and to permit persons to whom the Software is
  11. furnished to do so, subject to the following conditions:
  12. The above copyright notice and this permission notice shall be included in
  13. all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. THE SOFTWARE.
  21. ****************************************************************************/
  22. /**
  23. * @constant
  24. * @type Number
  25. */
  26. cc.MENU_STATE_WAITING = 0;
  27. /**
  28. * @constant
  29. * @type Number
  30. */
  31. cc.MENU_STATE_TRACKING_TOUCH = 1;
  32. /**
  33. * @constant
  34. * @type Number
  35. */
  36. cc.MENU_HANDLER_PRIORITY = -128;
  37. /**
  38. * @constant
  39. * @type Number
  40. */
  41. cc.DEFAULT_PADDING = 5;
  42. /**
  43. *<p> Features and Limitation:<br/>
  44. * - You can add MenuItem objects in runtime using addChild:<br/>
  45. * - But the only accepted children are MenuItem objects</p>
  46. * @class
  47. * @extends cc.Layer
  48. * @param {...cc.MenuItem|null} menuItems}
  49. * @example
  50. * var layer = new cc.Menu(menuitem1, menuitem2, menuitem3);
  51. */
  52. cc.Menu = cc.Layer.extend(/** @lends cc.Menu# */{
  53. enabled: false,
  54. _color: null,
  55. _opacity: 0,
  56. _selectedItem: null,
  57. _state: -1,
  58. _touchListener: null,
  59. _className: "Menu",
  60. /**
  61. * Constructor of cc.Menu override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
  62. * @param {...cc.MenuItem|null} menuItems}
  63. */
  64. ctor: function (menuItems) {
  65. cc.Layer.prototype.ctor.call(this);
  66. this._color = cc.color.WHITE;
  67. this.enabled = false;
  68. this._opacity = 255;
  69. this._selectedItem = null;
  70. this._state = -1;
  71. this._touchListener = cc.EventListener.create({
  72. event: cc.EventListener.TOUCH_ONE_BY_ONE,
  73. swallowTouches: true,
  74. onTouchBegan: this._onTouchBegan,
  75. onTouchMoved: this._onTouchMoved,
  76. onTouchEnded: this._onTouchEnded,
  77. onTouchCancelled: this._onTouchCancelled
  78. });
  79. if ((arguments.length > 0) && (arguments[arguments.length - 1] == null))
  80. cc.log("parameters should not be ending with null in Javascript");
  81. var argc = arguments.length, items;
  82. if (argc == 0) {
  83. items = [];
  84. } else if (argc == 1) {
  85. if (menuItems instanceof Array) {
  86. items = menuItems;
  87. }
  88. else items = [menuItems];
  89. }
  90. else if (argc > 1) {
  91. items = [];
  92. for (var i = 0; i < argc; i++) {
  93. if (arguments[i])
  94. items.push(arguments[i]);
  95. }
  96. }
  97. this.initWithArray(items);
  98. },
  99. /**
  100. * <p>
  101. * Event callback that is invoked every time when CCMenu enters the 'stage'. <br/>
  102. * If the CCMenu enters the 'stage' with a transition, this event is called when the transition starts. <br/>
  103. * During onEnter you can't access a "sister/brother" node. <br/>
  104. * If you override onEnter, you must call its parent's onEnter function with this._super().
  105. * </p>
  106. */
  107. onEnter: function () {
  108. var locListener = this._touchListener;
  109. if (!locListener._isRegistered())
  110. cc.eventManager.addListener(locListener, this);
  111. cc.Node.prototype.onEnter.call(this);
  112. },
  113. /**
  114. * return the color for cc.Menu
  115. * @return {cc.Color}
  116. */
  117. getColor: function () {
  118. var locColor = this._color;
  119. return cc.color(locColor.r, locColor.g, locColor.b, locColor.a);
  120. },
  121. /**
  122. * set the color for cc.Menu
  123. * @param {cc.Color} color
  124. */
  125. setColor: function (color) {
  126. var locColor = this._color;
  127. locColor.r = color.r;
  128. locColor.g = color.g;
  129. locColor.b = color.b;
  130. var locChildren = this._children;
  131. if (locChildren && locChildren.length > 0) {
  132. for (var i = 0; i < locChildren.length; i++) {
  133. locChildren[i].setColor(color);
  134. }
  135. }
  136. if (color.a !== undefined && !color.a_undefined) {
  137. this.setOpacity(color.a);
  138. }
  139. },
  140. /**
  141. * return the opacity for this menu
  142. * @return {Number}
  143. */
  144. getOpacity: function () {
  145. return this._opacity;
  146. },
  147. /**
  148. * set the opacity for this menu
  149. * @param {Number} opa
  150. */
  151. setOpacity: function (opa) {
  152. this._opacity = opa;
  153. var locChildren = this._children;
  154. if (locChildren && locChildren.length > 0) {
  155. for (var i = 0; i < locChildren.length; i++)
  156. locChildren[i].setOpacity(opa);
  157. }
  158. this._color.a = opa;
  159. },
  160. /**
  161. * return whether or not the menu will receive events
  162. * @return {Boolean}
  163. */
  164. isEnabled: function () {
  165. return this.enabled;
  166. },
  167. /**
  168. * set whether or not the menu will receive events
  169. * @param {Boolean} enabled
  170. */
  171. setEnabled: function (enabled) {
  172. this.enabled = enabled;
  173. },
  174. /**
  175. * initializes a cc.Menu with it's items
  176. * @param {Array} args
  177. * @return {Boolean}
  178. */
  179. initWithItems: function (args) {
  180. var pArray = [];
  181. if (args) {
  182. for (var i = 0; i < args.length; i++) {
  183. if (args[i])
  184. pArray.push(args[i]);
  185. }
  186. }
  187. return this.initWithArray(pArray);
  188. },
  189. /**
  190. * initializes a cc.Menu with a Array of cc.MenuItem objects
  191. * @param {Array} array Of cc.MenuItem Items
  192. * @return {Boolean}
  193. */
  194. initWithArray: function (arrayOfItems) {
  195. if (cc.Layer.prototype.init.call(this)) {
  196. this.enabled = true;
  197. // menu in the center of the screen
  198. var winSize = cc.winSize;
  199. this.setPosition(winSize.width / 2, winSize.height / 2);
  200. this.setContentSize(winSize);
  201. this.setAnchorPoint(0.5, 0.5);
  202. this.ignoreAnchorPointForPosition(true);
  203. if (arrayOfItems) {
  204. for (var i = 0; i < arrayOfItems.length; i++)
  205. this.addChild(arrayOfItems[i], i);
  206. }
  207. this._selectedItem = null;
  208. this._state = cc.MENU_STATE_WAITING;
  209. // enable cascade color and opacity on menus
  210. this.cascadeColor = true;
  211. this.cascadeOpacity = true;
  212. return true;
  213. }
  214. return false;
  215. },
  216. /**
  217. * add a child for cc.Menu
  218. * @param {cc.Node} child
  219. * @param {Number|Null} [zOrder=] zOrder for the child
  220. * @param {Number|Null} [tag=] tag for the child
  221. */
  222. addChild: function (child, zOrder, tag) {
  223. if (!(child instanceof cc.MenuItem))
  224. throw "cc.Menu.addChild() : Menu only supports MenuItem objects as children";
  225. cc.Layer.prototype.addChild.call(this, child, zOrder, tag);
  226. },
  227. /**
  228. * align items vertically with default padding
  229. */
  230. alignItemsVertically: function () {
  231. this.alignItemsVerticallyWithPadding(cc.DEFAULT_PADDING);
  232. },
  233. /**
  234. * align items vertically with specified padding
  235. * @param {Number} padding
  236. */
  237. alignItemsVerticallyWithPadding: function (padding) {
  238. var height = -padding, locChildren = this._children, len, i, locScaleY, locHeight, locChild;
  239. if (locChildren && locChildren.length > 0) {
  240. for (i = 0, len = locChildren.length; i < len; i++)
  241. height += locChildren[i].height * locChildren[i].scaleY + padding;
  242. var y = height / 2.0;
  243. for (i = 0, len = locChildren.length; i < len; i++) {
  244. locChild = locChildren[i];
  245. locHeight = locChild.height;
  246. locScaleY = locChild.scaleY;
  247. locChild.setPosition(0, y - locHeight * locScaleY / 2);
  248. y -= locHeight * locScaleY + padding;
  249. }
  250. }
  251. },
  252. /**
  253. * align items horizontally with default padding
  254. */
  255. alignItemsHorizontally: function () {
  256. this.alignItemsHorizontallyWithPadding(cc.DEFAULT_PADDING);
  257. },
  258. /**
  259. * align items horizontally with specified padding
  260. * @param {Number} padding
  261. */
  262. alignItemsHorizontallyWithPadding: function (padding) {
  263. var width = -padding, locChildren = this._children, i, len, locScaleX, locWidth, locChild;
  264. if (locChildren && locChildren.length > 0) {
  265. for (i = 0, len = locChildren.length; i < len; i++)
  266. width += locChildren[i].width * locChildren[i].scaleX + padding;
  267. var x = -width / 2.0;
  268. for (i = 0, len = locChildren.length; i < len; i++) {
  269. locChild = locChildren[i];
  270. locScaleX = locChild.scaleX;
  271. locWidth = locChildren[i].width;
  272. locChild.setPosition(x + locWidth * locScaleX / 2, 0);
  273. x += locWidth * locScaleX + padding;
  274. }
  275. }
  276. },
  277. /**
  278. * align items in columns
  279. * @example
  280. * // Example
  281. * menu.alignItemsInColumns(3,2,3)// this will create 3 columns, with 3 items for first column, 2 items for second and 3 for third
  282. *
  283. * menu.alignItemsInColumns(3,3)//this creates 2 columns, each have 3 items
  284. */
  285. alignItemsInColumns: function (/*Multiple Arguments*/) {
  286. if ((arguments.length > 0) && (arguments[arguments.length - 1] == null))
  287. cc.log("parameters should not be ending with null in Javascript");
  288. var rows = [];
  289. for (var i = 0; i < arguments.length; i++) {
  290. rows.push(arguments[i]);
  291. }
  292. var height = -5;
  293. var row = 0;
  294. var rowHeight = 0;
  295. var columnsOccupied = 0;
  296. var rowColumns, tmp, len;
  297. var locChildren = this._children;
  298. if (locChildren && locChildren.length > 0) {
  299. for (i = 0, len = locChildren.length; i < len; i++) {
  300. if (row >= rows.length)
  301. continue;
  302. rowColumns = rows[row];
  303. // can not have zero columns on a row
  304. if (!rowColumns)
  305. continue;
  306. tmp = locChildren[i].height;
  307. rowHeight = ((rowHeight >= tmp || isNaN(tmp)) ? rowHeight : tmp);
  308. ++columnsOccupied;
  309. if (columnsOccupied >= rowColumns) {
  310. height += rowHeight + 5;
  311. columnsOccupied = 0;
  312. rowHeight = 0;
  313. ++row;
  314. }
  315. }
  316. }
  317. // check if too many rows/columns for available menu items
  318. //cc.assert(!columnsOccupied, ""); //?
  319. var winSize = cc.director.getWinSize();
  320. row = 0;
  321. rowHeight = 0;
  322. rowColumns = 0;
  323. var w = 0.0;
  324. var x = 0.0;
  325. var y = (height / 2);
  326. if (locChildren && locChildren.length > 0) {
  327. for (i = 0, len = locChildren.length; i < len; i++) {
  328. var child = locChildren[i];
  329. if (rowColumns == 0) {
  330. rowColumns = rows[row];
  331. w = winSize.width / (1 + rowColumns);
  332. x = w;
  333. }
  334. tmp = child._getHeight();
  335. rowHeight = ((rowHeight >= tmp || isNaN(tmp)) ? rowHeight : tmp);
  336. child.setPosition(x - winSize.width / 2, y - tmp / 2);
  337. x += w;
  338. ++columnsOccupied;
  339. if (columnsOccupied >= rowColumns) {
  340. y -= rowHeight + 5;
  341. columnsOccupied = 0;
  342. rowColumns = 0;
  343. rowHeight = 0;
  344. ++row;
  345. }
  346. }
  347. }
  348. },
  349. /**
  350. * align menu items in rows
  351. * @param {Number}
  352. * @example
  353. * // Example
  354. * menu.alignItemsInRows(5,3)//this will align items to 2 rows, first row with 5 items, second row with 3
  355. *
  356. * menu.alignItemsInRows(4,4,4,4)//this creates 4 rows each have 4 items
  357. */
  358. alignItemsInRows: function (/*Multiple arguments*/) {
  359. if ((arguments.length > 0) && (arguments[arguments.length - 1] == null))
  360. cc.log("parameters should not be ending with null in Javascript");
  361. var columns = [], i;
  362. for (i = 0; i < arguments.length; i++) {
  363. columns.push(arguments[i]);
  364. }
  365. var columnWidths = [];
  366. var columnHeights = [];
  367. var width = -10;
  368. var columnHeight = -5;
  369. var column = 0;
  370. var columnWidth = 0;
  371. var rowsOccupied = 0;
  372. var columnRows, child, len, tmp;
  373. var locChildren = this._children;
  374. if (locChildren && locChildren.length > 0) {
  375. for (i = 0, len = locChildren.length; i < len; i++) {
  376. child = locChildren[i];
  377. // check if too many menu items for the amount of rows/columns
  378. if (column >= columns.length)
  379. continue;
  380. columnRows = columns[column];
  381. // can't have zero rows on a column
  382. if (!columnRows)
  383. continue;
  384. // columnWidth = fmaxf(columnWidth, [item contentSize].width);
  385. tmp = child.width;
  386. columnWidth = ((columnWidth >= tmp || isNaN(tmp)) ? columnWidth : tmp);
  387. columnHeight += (child.height + 5);
  388. ++rowsOccupied;
  389. if (rowsOccupied >= columnRows) {
  390. columnWidths.push(columnWidth);
  391. columnHeights.push(columnHeight);
  392. width += columnWidth + 10;
  393. rowsOccupied = 0;
  394. columnWidth = 0;
  395. columnHeight = -5;
  396. ++column;
  397. }
  398. }
  399. }
  400. // check if too many rows/columns for available menu items.
  401. //cc.assert(!rowsOccupied, "");
  402. var winSize = cc.director.getWinSize();
  403. column = 0;
  404. columnWidth = 0;
  405. columnRows = 0;
  406. var x = -width / 2;
  407. var y = 0.0;
  408. if (locChildren && locChildren.length > 0) {
  409. for (i = 0, len = locChildren.length; i < len; i++) {
  410. child = locChildren[i];
  411. if (columnRows == 0) {
  412. columnRows = columns[column];
  413. y = columnHeights[column];
  414. }
  415. // columnWidth = fmaxf(columnWidth, [item contentSize].width);
  416. tmp = child._getWidth();
  417. columnWidth = ((columnWidth >= tmp || isNaN(tmp)) ? columnWidth : tmp);
  418. child.setPosition(x + columnWidths[column] / 2, y - winSize.height / 2);
  419. y -= child.height + 10;
  420. ++rowsOccupied;
  421. if (rowsOccupied >= columnRows) {
  422. x += columnWidth + 5;
  423. rowsOccupied = 0;
  424. columnRows = 0;
  425. columnWidth = 0;
  426. ++column;
  427. }
  428. }
  429. }
  430. },
  431. /**
  432. * remove a child from cc.Menu
  433. * @param {cc.Node} child the child you want to remove
  434. * @param {boolean} cleanup whether to cleanup
  435. */
  436. removeChild: function (child, cleanup) {
  437. if (child == null)
  438. return;
  439. if (!(child instanceof cc.MenuItem)) {
  440. cc.log("cc.Menu.removeChild():Menu only supports MenuItem objects as children");
  441. return;
  442. }
  443. if (this._selectedItem == child)
  444. this._selectedItem = null;
  445. cc.Node.prototype.removeChild.call(this, child, cleanup);
  446. },
  447. _onTouchBegan: function (touch, event) {
  448. var target = event.getCurrentTarget();
  449. if (target._state != cc.MENU_STATE_WAITING || !target._visible || !target.enabled)
  450. return false;
  451. for (var c = target.parent; c != null; c = c.parent) {
  452. if (!c.isVisible())
  453. return false;
  454. }
  455. target._selectedItem = target._itemForTouch(touch);
  456. if (target._selectedItem) {
  457. target._state = cc.MENU_STATE_TRACKING_TOUCH;
  458. target._selectedItem.selected();
  459. return true;
  460. }
  461. return false;
  462. },
  463. _onTouchEnded: function (touch, event) {
  464. var target = event.getCurrentTarget();
  465. if (target._state !== cc.MENU_STATE_TRACKING_TOUCH) {
  466. cc.log("cc.Menu.onTouchEnded(): invalid state");
  467. return;
  468. }
  469. if (target._selectedItem) {
  470. target._selectedItem.unselected();
  471. target._selectedItem.activate();
  472. }
  473. target._state = cc.MENU_STATE_WAITING;
  474. },
  475. _onTouchCancelled: function (touch, event) {
  476. var target = event.getCurrentTarget();
  477. if (target._state !== cc.MENU_STATE_TRACKING_TOUCH) {
  478. cc.log("cc.Menu.onTouchCancelled(): invalid state");
  479. return;
  480. }
  481. if (this._selectedItem)
  482. target._selectedItem.unselected();
  483. target._state = cc.MENU_STATE_WAITING;
  484. },
  485. _onTouchMoved: function (touch, event) {
  486. var target = event.getCurrentTarget();
  487. if (target._state !== cc.MENU_STATE_TRACKING_TOUCH) {
  488. cc.log("cc.Menu.onTouchMoved(): invalid state");
  489. return;
  490. }
  491. var currentItem = target._itemForTouch(touch);
  492. if (currentItem != target._selectedItem) {
  493. if (target._selectedItem)
  494. target._selectedItem.unselected();
  495. target._selectedItem = currentItem;
  496. if (target._selectedItem)
  497. target._selectedItem.selected();
  498. }
  499. },
  500. /**
  501. * <p>
  502. * callback that is called every time the cc.Menu leaves the 'stage'. <br/>
  503. * If the cc.Menu leaves the 'stage' with a transition, this callback is called when the transition finishes. <br/>
  504. * During onExit you can't access a sibling node. <br/>
  505. * If you override onExit, you shall call its parent's onExit with this._super().
  506. * </p>
  507. */
  508. onExit: function () {
  509. if (this._state == cc.MENU_STATE_TRACKING_TOUCH) {
  510. if (this._selectedItem) {
  511. this._selectedItem.unselected();
  512. this._selectedItem = null;
  513. }
  514. this._state = cc.MENU_STATE_WAITING;
  515. }
  516. cc.Node.prototype.onExit.call(this);
  517. },
  518. /**
  519. * only use for jsbinding
  520. * @param value
  521. */
  522. setOpacityModifyRGB: function (value) {
  523. },
  524. /**
  525. * only use for jsbinding
  526. * @returns {boolean}
  527. */
  528. isOpacityModifyRGB: function () {
  529. return false;
  530. },
  531. _itemForTouch: function (touch) {
  532. var touchLocation = touch.getLocation();
  533. var itemChildren = this._children, locItemChild;
  534. if (itemChildren && itemChildren.length > 0) {
  535. for (var i = 0; i < itemChildren.length; i++) {
  536. locItemChild = itemChildren[i];
  537. if (locItemChild.isVisible() && locItemChild.isEnabled()) {
  538. var local = locItemChild.convertToNodeSpace(touchLocation);
  539. var r = locItemChild.rect();
  540. r.x = 0;
  541. r.y = 0;
  542. if (cc.rectContainsPoint(r, local))
  543. return locItemChild;
  544. }
  545. }
  546. }
  547. return null;
  548. }
  549. });
  550. var _p = cc.Menu.prototype;
  551. // Extended properties
  552. /** @expose */
  553. _p.enabled;
  554. /**
  555. * create a new menu
  556. * @deprecated since v3.0, please use new cc.Menu(menuitem1, menuitem2, menuitem3) to create a new menu
  557. * @param {...cc.MenuItem|null} menuItems
  558. * @return {cc.Menu}
  559. * @example
  560. * // Example
  561. * //there is no limit on how many menu item you can pass in
  562. * var myMenu = cc.Menu.create(menuitem1, menuitem2, menuitem3);
  563. */
  564. cc.Menu.create = function (menuItems) {
  565. var argc = arguments.length;
  566. if ((argc > 0) && (arguments[argc - 1] == null))
  567. cc.log("parameters should not be ending with null in Javascript");
  568. var ret;
  569. if (argc == 0)
  570. ret = new cc.Menu();
  571. else if (argc == 1)
  572. ret = new cc.Menu(menuItems);
  573. else
  574. ret = new cc.Menu(Array.prototype.slice.call(arguments, 0));
  575. return ret;
  576. };