Container.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221
  1. #include "Base.h"
  2. #include "Container.h"
  3. #include "Layout.h"
  4. #include "AbsoluteLayout.h"
  5. #include "FlowLayout.h"
  6. #include "VerticalLayout.h"
  7. #include "Label.h"
  8. #include "Button.h"
  9. #include "CheckBox.h"
  10. #include "RadioButton.h"
  11. #include "Slider.h"
  12. #include "TextBox.h"
  13. #include "Joystick.h"
  14. #include "Game.h"
  15. namespace gameplay
  16. {
  17. // If the user stops scrolling for this amount of time (in millis) before touch/click release, don't apply inertia.
  18. static const long SCROLL_INERTIA_DELAY = 100L;
  19. // Factor to multiply friction by before applying to velocity.
  20. static const float SCROLL_FRICTION_FACTOR = 5.0f;
  21. // Distance that must be scrolled before isScrolling() will return true, used e.g. to cancel button-click events.
  22. static const float SCROLL_THRESHOLD = 10.0f;
  23. /**
  24. * Sort function for use with _controls.sort(), based on Z-Order.
  25. *
  26. * @param c1 The first control
  27. * @param c2 The second control
  28. * return true if the first controls z index is less than the second.
  29. */
  30. static bool sortControlsByZOrder(Control* c1, Control* c2);
  31. Container::Container()
  32. : _layout(NULL), _scrollBarTopCap(NULL), _scrollBarVertical(NULL), _scrollBarBottomCap(NULL),
  33. _scrollBarLeftCap(NULL), _scrollBarHorizontal(NULL), _scrollBarRightCap(NULL),
  34. _scroll(SCROLL_NONE), _scrollBarBounds(Rectangle::empty()), _scrollPosition(Vector2::zero()),
  35. _scrollBarsAutoHide(false), _scrollBarOpacity(1.0f), _scrolling(false),
  36. _scrollingVeryFirstX(0), _scrollingVeryFirstY(0), _scrollingFirstX(0), _scrollingFirstY(0), _scrollingLastX(0), _scrollingLastY(0),
  37. _scrollingStartTimeX(0), _scrollingStartTimeY(0), _scrollingLastTime(0),
  38. _scrollingVelocity(Vector2::zero()), _scrollingFriction(1.0f),
  39. _scrollingRight(false), _scrollingDown(false),
  40. _scrollingMouseVertically(false), _scrollingMouseHorizontally(false),
  41. _scrollBarOpacityClip(NULL), _zIndexDefault(0), _focusIndexDefault(0), _focusIndexMax(0), _totalWidth(0), _totalHeight(0),
  42. _contactIndices(0), _initializedWithScroll(false)
  43. {
  44. }
  45. Container::~Container()
  46. {
  47. std::vector<Control*>::iterator it;
  48. for (it = _controls.begin(); it < _controls.end(); it++)
  49. {
  50. SAFE_RELEASE((*it));
  51. }
  52. SAFE_RELEASE(_layout);
  53. }
  54. Container* Container::create(const char* id, Theme::Style* style, Layout::Type layoutType)
  55. {
  56. GP_ASSERT(style);
  57. Container* container = Container::create(layoutType);
  58. if (id)
  59. container->_id = id;
  60. container->_style = style;
  61. return container;
  62. }
  63. Container* Container::create(Layout::Type type)
  64. {
  65. Layout* layout = NULL;
  66. switch (type)
  67. {
  68. case Layout::LAYOUT_ABSOLUTE:
  69. layout = AbsoluteLayout::create();
  70. break;
  71. case Layout::LAYOUT_FLOW:
  72. layout = FlowLayout::create();
  73. break;
  74. case Layout::LAYOUT_VERTICAL:
  75. layout = VerticalLayout::create();
  76. break;
  77. }
  78. Container* container = new Container();
  79. container->_layout = layout;
  80. return container;
  81. }
  82. Container* Container::create(Theme::Style* style, Properties* properties, Theme* theme)
  83. {
  84. GP_ASSERT(properties);
  85. const char* layoutString = properties->getString("layout");
  86. Container* container = Container::create(getLayoutType(layoutString));
  87. container->initialize(style, properties);
  88. container->_scroll = getScroll(properties->getString("scroll"));
  89. container->_scrollBarsAutoHide = properties->getBool("scrollBarsAutoHide");
  90. if (container->_scrollBarsAutoHide)
  91. {
  92. container->_scrollBarOpacity = 0.0f;
  93. }
  94. container->addControls(theme, properties);
  95. container->_layout->update(container, container->_scrollPosition);
  96. return container;
  97. }
  98. void Container::addControls(Theme* theme, Properties* properties)
  99. {
  100. GP_ASSERT(theme);
  101. GP_ASSERT(properties);
  102. // Add all the controls to this container.
  103. Properties* controlSpace = properties->getNextNamespace();
  104. while (controlSpace != NULL)
  105. {
  106. Control* control = NULL;
  107. const char* controlStyleName = controlSpace->getString("style");
  108. Theme::Style* controlStyle = NULL;
  109. if (controlStyleName)
  110. {
  111. controlStyle = theme->getStyle(controlStyleName);
  112. }
  113. else
  114. {
  115. controlStyle = theme->getEmptyStyle();
  116. }
  117. std::string controlName(controlSpace->getNamespace());
  118. std::transform(controlName.begin(), controlName.end(), controlName.begin(), (int(*)(int))toupper);
  119. if (controlName == "LABEL")
  120. {
  121. control = Label::create(controlStyle, controlSpace);
  122. }
  123. else if (controlName == "BUTTON")
  124. {
  125. control = Button::create(controlStyle, controlSpace);
  126. }
  127. else if (controlName == "CHECKBOX")
  128. {
  129. control = CheckBox::create(controlStyle, controlSpace);
  130. }
  131. else if (controlName == "RADIOBUTTON")
  132. {
  133. control = RadioButton::create(controlStyle, controlSpace);
  134. }
  135. else if (controlName == "CONTAINER")
  136. {
  137. control = Container::create(controlStyle, controlSpace, theme);
  138. }
  139. else if (controlName == "SLIDER")
  140. {
  141. control = Slider::create(controlStyle, controlSpace);
  142. }
  143. else if (controlName == "TEXTBOX")
  144. {
  145. control = TextBox::create(controlStyle, controlSpace);
  146. }
  147. else if (controlName == "JOYSTICK")
  148. {
  149. control = Joystick::create(controlStyle, controlSpace);
  150. }
  151. else
  152. {
  153. // Ignore - not a valid control name.
  154. // This used to fail, but I see no reason to hard fail here (this also fixes not being able
  155. // to set padding on containers).
  156. }
  157. // Add the new control to the form.
  158. if (control)
  159. {
  160. addControl(control);
  161. control->release();
  162. if (control->getZIndex() == -1)
  163. {
  164. control->setZIndex(_zIndexDefault++);
  165. }
  166. if (control->getFocusIndex() == -1)
  167. {
  168. control->setFocusIndex(_focusIndexDefault++);
  169. }
  170. int focusIndex = control->getFocusIndex();
  171. if (focusIndex > _focusIndexMax)
  172. _focusIndexMax = focusIndex;
  173. }
  174. // Get the next control.
  175. controlSpace = properties->getNextNamespace();
  176. }
  177. // Sort controls by Z-Order.
  178. std::sort(_controls.begin(), _controls.end(), &sortControlsByZOrder);
  179. }
  180. Layout* Container::getLayout()
  181. {
  182. return _layout;
  183. }
  184. unsigned int Container::addControl(Control* control)
  185. {
  186. GP_ASSERT(control);
  187. if (control->_parent && control->_parent != this)
  188. {
  189. control->_parent->removeControl(control);
  190. }
  191. if (control->_parent != this)
  192. {
  193. _controls.push_back(control);
  194. control->addRef();
  195. control->_parent = this;
  196. return (unsigned int)(_controls.size() - 1);
  197. }
  198. else
  199. {
  200. // Control is already in this container.
  201. // Do nothing but determine and return control's index.
  202. const size_t size = _controls.size();
  203. for (size_t i = 0; i < size; ++i)
  204. {
  205. Control* c = _controls[i];
  206. if (c == control)
  207. {
  208. return (unsigned int)i;
  209. }
  210. }
  211. // Should never reach this.
  212. GP_ASSERT(false);
  213. return 0;
  214. }
  215. }
  216. void Container::insertControl(Control* control, unsigned int index)
  217. {
  218. GP_ASSERT(control);
  219. if (control->_parent && control->_parent != this)
  220. {
  221. control->_parent->removeControl(control);
  222. }
  223. if (control->_parent != this)
  224. {
  225. std::vector<Control*>::iterator it = _controls.begin() + index;
  226. _controls.insert(it, control);
  227. control->addRef();
  228. control->_parent = this;
  229. }
  230. }
  231. void Container::removeControl(unsigned int index)
  232. {
  233. GP_ASSERT(index < _controls.size());
  234. std::vector<Control*>::iterator it = _controls.begin() + index;
  235. _controls.erase(it);
  236. Control* control = *it;
  237. control->_parent = NULL;
  238. SAFE_RELEASE(control);
  239. }
  240. void Container::removeControl(const char* id)
  241. {
  242. GP_ASSERT(id);
  243. std::vector<Control*>::iterator it;
  244. for (it = _controls.begin(); it < _controls.end(); it++)
  245. {
  246. Control* c = *it;
  247. if (strcmp(id, c->getId()) == 0)
  248. {
  249. c->_parent = NULL;
  250. SAFE_RELEASE(c);
  251. _controls.erase(it);
  252. return;
  253. }
  254. }
  255. }
  256. void Container::removeControl(Control* control)
  257. {
  258. GP_ASSERT(control);
  259. std::vector<Control*>::iterator it;
  260. for (it = _controls.begin(); it < _controls.end(); it++)
  261. {
  262. if (*it == control)
  263. {
  264. control->_parent = NULL;
  265. SAFE_RELEASE(control);
  266. _controls.erase(it);
  267. return;
  268. }
  269. }
  270. }
  271. Control* Container::getControl(unsigned int index) const
  272. {
  273. std::vector<Control*>::const_iterator it = _controls.begin() + index;
  274. return *it;
  275. }
  276. Control* Container::getControl(const char* id) const
  277. {
  278. GP_ASSERT(id);
  279. std::vector<Control*>::const_iterator it;
  280. for (it = _controls.begin(); it < _controls.end(); it++)
  281. {
  282. Control* c = *it;
  283. GP_ASSERT(c);
  284. if (strcmp(id, c->getId()) == 0)
  285. {
  286. return c;
  287. }
  288. else if (c->isContainer())
  289. {
  290. Control* cc = ((Container*)c)->getControl(id);
  291. if (cc)
  292. {
  293. return cc;
  294. }
  295. }
  296. }
  297. return NULL;
  298. }
  299. const std::vector<Control*>& Container::getControls() const
  300. {
  301. return _controls;
  302. }
  303. void Container::setScroll(Scroll scroll)
  304. {
  305. if (scroll != _scroll)
  306. {
  307. _scroll = scroll;
  308. _dirty = true;
  309. }
  310. }
  311. Container::Scroll Container::getScroll() const
  312. {
  313. return _scroll;
  314. }
  315. void Container::setScrollBarsAutoHide(bool autoHide)
  316. {
  317. if (autoHide != _scrollBarsAutoHide)
  318. {
  319. _scrollBarsAutoHide = autoHide;
  320. _dirty = true;
  321. }
  322. }
  323. bool Container::isScrollBarsAutoHide() const
  324. {
  325. return _scrollBarsAutoHide;
  326. }
  327. bool Container::isScrolling() const
  328. {
  329. if (_parent && _parent->isScrolling())
  330. return true;
  331. return (_scrolling &&
  332. (abs(_scrollingLastX - _scrollingVeryFirstX) > SCROLL_THRESHOLD ||
  333. abs(_scrollingLastY - _scrollingVeryFirstY) > SCROLL_THRESHOLD));
  334. }
  335. Animation* Container::getAnimation(const char* id) const
  336. {
  337. std::vector<Control*>::const_iterator itr = _controls.begin();
  338. std::vector<Control*>::const_iterator end = _controls.end();
  339. Control* control = NULL;
  340. for (; itr != end; itr++)
  341. {
  342. control = *itr;
  343. GP_ASSERT(control);
  344. Animation* animation = control->getAnimation(id);
  345. if (animation)
  346. return animation;
  347. if (control->isContainer())
  348. {
  349. animation = ((Container*)control)->getAnimation(id);
  350. if (animation)
  351. return animation;
  352. }
  353. }
  354. return NULL;
  355. }
  356. const char* Container::getType() const
  357. {
  358. return "container";
  359. }
  360. void Container::update(const Control* container, const Vector2& offset)
  361. {
  362. // Update this container's viewport.
  363. Control::update(container, offset);
  364. // Get scrollbar images and diminish clipping bounds to make room for scrollbars.
  365. if ((_scroll & SCROLL_HORIZONTAL) == SCROLL_HORIZONTAL)
  366. {
  367. _scrollBarLeftCap = getImage("scrollBarLeftCap", _state);
  368. _scrollBarHorizontal = getImage("horizontalScrollBar", _state);
  369. _scrollBarRightCap = getImage("scrollBarRightCap", _state);
  370. GP_ASSERT(_scrollBarLeftCap && _scrollBarHorizontal && _scrollBarRightCap);
  371. _viewportClipBounds.height -= _scrollBarHorizontal->getRegion().height;
  372. }
  373. if ((_scroll & SCROLL_VERTICAL) == SCROLL_VERTICAL)
  374. {
  375. _scrollBarTopCap = getImage("scrollBarTopCap", _state);
  376. _scrollBarVertical = getImage("verticalScrollBar", _state);
  377. _scrollBarBottomCap = getImage("scrollBarBottomCap", _state);
  378. GP_ASSERT(_scrollBarTopCap && _scrollBarVertical && _scrollBarBottomCap);
  379. _viewportClipBounds.width -= _scrollBarVertical->getRegion().width;
  380. }
  381. // Sort controls by Z-Order.
  382. std::sort(_controls.begin(), _controls.end(), &sortControlsByZOrder);
  383. GP_ASSERT(_layout);
  384. if (_scroll != SCROLL_NONE)
  385. {
  386. updateScroll();
  387. }
  388. else
  389. {
  390. _layout->update(this, Vector2::zero());
  391. }
  392. }
  393. void Container::draw(SpriteBatch* spriteBatch, const Rectangle& clip, bool needsClear, bool cleared, float targetHeight)
  394. {
  395. if (needsClear)
  396. {
  397. GL_ASSERT( glEnable(GL_SCISSOR_TEST) );
  398. float clearY = targetHeight - _clearBounds.y - _clearBounds.height;
  399. GL_ASSERT( glScissor(_clearBounds.x, clearY, _clearBounds.width, _clearBounds.height) );
  400. Game::getInstance()->clear(Game::CLEAR_COLOR, Vector4::zero(), 1.0f, 0);
  401. GL_ASSERT( glDisable(GL_SCISSOR_TEST) );
  402. needsClear = false;
  403. cleared = true;
  404. }
  405. else if (!cleared)
  406. {
  407. needsClear = true;
  408. }
  409. if (!_visible)
  410. return;
  411. spriteBatch->start();
  412. Control::drawBorder(spriteBatch, clip);
  413. spriteBatch->finish();
  414. std::vector<Control*>::const_iterator it;
  415. Rectangle boundsUnion = Rectangle::empty();
  416. for (it = _controls.begin(); it < _controls.end(); it++)
  417. {
  418. Control* control = *it;
  419. GP_ASSERT(control);
  420. if (!needsClear || control->isDirty() || control->_clearBounds.intersects(boundsUnion))
  421. {
  422. control->draw(spriteBatch, _viewportClipBounds, needsClear, cleared, targetHeight);
  423. Rectangle::combine(control->_clearBounds, boundsUnion, &boundsUnion);
  424. }
  425. }
  426. if (_scroll != SCROLL_NONE && (_scrollBarOpacity > 0.0f))
  427. {
  428. // Draw scroll bars.
  429. Rectangle clipRegion(_viewportClipBounds);
  430. spriteBatch->start();
  431. if (_scrollBarBounds.height > 0 &&((_scroll & SCROLL_VERTICAL) == SCROLL_VERTICAL))
  432. {
  433. const Rectangle& topRegion = _scrollBarTopCap->getRegion();
  434. const Theme::UVs& topUVs = _scrollBarTopCap->getUVs();
  435. Vector4 topColor = _scrollBarTopCap->getColor();
  436. topColor.w *= _scrollBarOpacity * _opacity;
  437. const Rectangle& verticalRegion = _scrollBarVertical->getRegion();
  438. const Theme::UVs& verticalUVs = _scrollBarVertical->getUVs();
  439. Vector4 verticalColor = _scrollBarVertical->getColor();
  440. verticalColor.w *= _scrollBarOpacity * _opacity;
  441. const Rectangle& bottomRegion = _scrollBarBottomCap->getRegion();
  442. const Theme::UVs& bottomUVs = _scrollBarBottomCap->getUVs();
  443. Vector4 bottomColor = _scrollBarBottomCap->getColor();
  444. bottomColor.w *= _scrollBarOpacity * _opacity;
  445. clipRegion.width += verticalRegion.width;
  446. Rectangle bounds(_viewportBounds.x + _viewportBounds.width - verticalRegion.width, _viewportBounds.y + _scrollBarBounds.y, topRegion.width, topRegion.height);
  447. spriteBatch->draw(bounds.x, bounds.y, bounds.width, bounds.height, topUVs.u1, topUVs.v1, topUVs.u2, topUVs.v2, topColor, clipRegion);
  448. bounds.y += topRegion.height;
  449. bounds.height = _scrollBarBounds.height - topRegion.height - bottomRegion.height;
  450. spriteBatch->draw(bounds.x, bounds.y, bounds.width, bounds.height, verticalUVs.u1, verticalUVs.v1, verticalUVs.u2, verticalUVs.v2, verticalColor, clipRegion);
  451. bounds.y += bounds.height;
  452. bounds.height = bottomRegion.height;
  453. spriteBatch->draw(bounds.x, bounds.y, bounds.width, bounds.height, bottomUVs.u1, bottomUVs.v1, bottomUVs.u2, bottomUVs.v2, bottomColor, clipRegion);
  454. }
  455. if (_scrollBarBounds.width > 0 && ((_scroll & SCROLL_HORIZONTAL) == SCROLL_HORIZONTAL))
  456. {
  457. const Rectangle& leftRegion = _scrollBarLeftCap->getRegion();
  458. const Theme::UVs& leftUVs = _scrollBarLeftCap->getUVs();
  459. Vector4 leftColor = _scrollBarLeftCap->getColor();
  460. leftColor.w *= _scrollBarOpacity * _opacity;
  461. const Rectangle& horizontalRegion = _scrollBarHorizontal->getRegion();
  462. const Theme::UVs& horizontalUVs = _scrollBarHorizontal->getUVs();
  463. Vector4 horizontalColor = _scrollBarHorizontal->getColor();
  464. horizontalColor.w *= _scrollBarOpacity * _opacity;
  465. const Rectangle& rightRegion = _scrollBarRightCap->getRegion();
  466. const Theme::UVs& rightUVs = _scrollBarRightCap->getUVs();
  467. Vector4 rightColor = _scrollBarRightCap->getColor();
  468. rightColor.w *= _scrollBarOpacity * _opacity;
  469. clipRegion.height += horizontalRegion.height;
  470. Rectangle bounds(_viewportBounds.x + _scrollBarBounds.x, _viewportBounds.y + _viewportBounds.height - horizontalRegion.height, leftRegion.width, leftRegion.height);
  471. spriteBatch->draw(bounds.x, bounds.y, bounds.width, bounds.height, leftUVs.u1, leftUVs.v1, leftUVs.u2, leftUVs.v2, leftColor, clipRegion);
  472. bounds.x += leftRegion.width;
  473. bounds.width = _scrollBarBounds.width - leftRegion.width - rightRegion.width;
  474. spriteBatch->draw(bounds.x, bounds.y, bounds.width, bounds.height, horizontalUVs.u1, horizontalUVs.v1, horizontalUVs.u2, horizontalUVs.v2, horizontalColor, clipRegion);
  475. bounds.x += bounds.width;
  476. bounds.width = rightRegion.width;
  477. spriteBatch->draw(bounds.x, bounds.y, bounds.width, bounds.height, rightUVs.u1, rightUVs.v1, rightUVs.u2, rightUVs.v2, rightColor, clipRegion);
  478. }
  479. spriteBatch->finish();
  480. if (_scrollingVelocity.isZero())
  481. {
  482. _dirty = false;
  483. }
  484. }
  485. else
  486. {
  487. _dirty = false;
  488. }
  489. }
  490. bool Container::isDirty()
  491. {
  492. if (_dirty)
  493. {
  494. return true;
  495. }
  496. else
  497. {
  498. std::vector<Control*>::const_iterator it;
  499. for (it = _controls.begin(); it < _controls.end(); it++)
  500. {
  501. GP_ASSERT(*it);
  502. if ((*it)->isDirty())
  503. {
  504. return true;
  505. }
  506. }
  507. }
  508. return false;
  509. }
  510. bool Container::touchEvent(Touch::TouchEvent evt, int x, int y, unsigned int contactIndex)
  511. {
  512. return pointerEvent(false, evt, x, y, (int)contactIndex);
  513. }
  514. bool Container::mouseEvent(Mouse::MouseEvent evt, int x, int y, int wheelDelta)
  515. {
  516. return pointerEvent(true, evt, x, y, wheelDelta);
  517. }
  518. bool Container::keyEvent(Keyboard::KeyEvent evt, int key)
  519. {
  520. // This event may run untrusted code by notifying listeners of events.
  521. // If the user calls exit() or otherwise releases this container, we
  522. // need to keep it alive until the method returns.
  523. addRef();
  524. std::vector<Control*>::const_iterator it;
  525. for (it = _controls.begin(); it < _controls.end(); it++)
  526. {
  527. Control* control = *it;
  528. GP_ASSERT(control);
  529. if (!control->isEnabled() || !control->isVisible())
  530. {
  531. continue;
  532. }
  533. if (control->getState() == Control::FOCUS)
  534. {
  535. if (control->keyEvent(evt, key))
  536. {
  537. release();
  538. return true;
  539. }
  540. else if (evt == Keyboard::KEY_CHAR && key == Keyboard::KEY_TAB)
  541. {
  542. // Shift focus to next control.
  543. int focusIndex = control->getFocusIndex() + 1; // Index to search for.
  544. if (focusIndex > _focusIndexMax)
  545. {
  546. focusIndex = 0;
  547. }
  548. control->setState(Control::NORMAL);
  549. std::vector<Control*>::const_iterator itt;
  550. for (itt = _controls.begin(); itt < _controls.end(); itt++)
  551. {
  552. Control* nextControl = *itt;
  553. if (nextControl->getFocusIndex() == focusIndex)
  554. {
  555. nextControl->setState(Control::FOCUS);
  556. release();
  557. return _consumeInputEvents;
  558. }
  559. }
  560. }
  561. }
  562. }
  563. release();
  564. return false;
  565. }
  566. bool Container::isContainer() const
  567. {
  568. return true;
  569. }
  570. Layout::Type Container::getLayoutType(const char* layoutString)
  571. {
  572. if (!layoutString)
  573. {
  574. return Layout::LAYOUT_ABSOLUTE;
  575. }
  576. std::string layoutName(layoutString);
  577. std::transform(layoutName.begin(), layoutName.end(), layoutName.begin(), (int(*)(int))toupper);
  578. if (layoutName == "LAYOUT_ABSOLUTE")
  579. {
  580. return Layout::LAYOUT_ABSOLUTE;
  581. }
  582. else if (layoutName == "LAYOUT_VERTICAL")
  583. {
  584. return Layout::LAYOUT_VERTICAL;
  585. }
  586. else if (layoutName == "LAYOUT_FLOW")
  587. {
  588. return Layout::LAYOUT_FLOW;
  589. }
  590. else
  591. {
  592. // Default.
  593. return Layout::LAYOUT_ABSOLUTE;
  594. }
  595. }
  596. void Container::updateScroll()
  597. {
  598. if (!_initializedWithScroll)
  599. {
  600. _initializedWithScroll = true;
  601. _layout->update(this, _scrollPosition);
  602. }
  603. // Update Time.
  604. static double lastFrameTime = Game::getGameTime();
  605. double frameTime = Game::getGameTime();
  606. float elapsedTime = (float)(frameTime - lastFrameTime);
  607. lastFrameTime = frameTime;
  608. const Theme::Border& containerBorder = getBorder(_state);
  609. const Theme::Padding& containerPadding = getPadding();
  610. // Calculate total width and height.
  611. std::vector<Control*> controls = getControls();
  612. for (size_t i = 0, controlsCount = controls.size(); i < controlsCount; i++)
  613. {
  614. Control* control = controls.at(i);
  615. const Rectangle& bounds = control->getBounds();
  616. const Theme::Margin& margin = control->getMargin();
  617. float newWidth = bounds.x + bounds.width;
  618. if (newWidth > _totalWidth)
  619. {
  620. _totalWidth = newWidth;
  621. }
  622. float newHeight = bounds.y + bounds.height;
  623. if (newHeight > _totalHeight)
  624. {
  625. _totalHeight = newHeight;
  626. }
  627. }
  628. float vWidth = getImageRegion("verticalScrollBar", _state).width;
  629. float hHeight = getImageRegion("horizontalScrollBar", _state).height;
  630. float clipWidth = _bounds.width - containerBorder.left - containerBorder.right - containerPadding.left - containerPadding.right - vWidth;
  631. float clipHeight = _bounds.height - containerBorder.top - containerBorder.bottom - containerPadding.top - containerPadding.bottom - hHeight;
  632. // Apply and dampen inertia.
  633. if (!_scrolling && !_scrollingVelocity.isZero())
  634. {
  635. // Calculate the time passed since last update.
  636. float elapsedSecs = (float)elapsedTime * 0.001f;
  637. _scrollPosition.x += _scrollingVelocity.x * elapsedSecs;
  638. _scrollPosition.y += _scrollingVelocity.y * elapsedSecs;
  639. float dampening = 1.0f - _scrollingFriction * SCROLL_FRICTION_FACTOR * elapsedSecs;
  640. _scrollingVelocity.x *= dampening;
  641. _scrollingVelocity.y *= dampening;
  642. if (fabs(_scrollingVelocity.x) < 100.0f)
  643. _scrollingVelocity.x = 0.0f;
  644. if (fabs(_scrollingVelocity.y) < 100.0f)
  645. _scrollingVelocity.y = 0.0f;
  646. }
  647. // Stop scrolling when the far edge is reached.
  648. if (-_scrollPosition.x > _totalWidth - clipWidth)
  649. {
  650. _scrollPosition.x = -(_totalWidth - clipWidth);
  651. _scrollingVelocity.x = 0;
  652. }
  653. if (-_scrollPosition.y > _totalHeight - clipHeight)
  654. {
  655. _scrollPosition.y = -(_totalHeight - clipHeight);
  656. _scrollingVelocity.y = 0;
  657. }
  658. if (_scrollPosition.x > 0)
  659. {
  660. _scrollPosition.x = 0;
  661. _scrollingVelocity.x = 0;
  662. }
  663. if (_scrollPosition.y > 0)
  664. {
  665. _scrollPosition.y = 0;
  666. _scrollingVelocity.y = 0;
  667. }
  668. float scrollWidth = 0;
  669. if (clipWidth < _totalWidth)
  670. scrollWidth = (clipWidth / _totalWidth) * clipWidth;
  671. float scrollHeight = 0;
  672. if (clipHeight < _totalHeight)
  673. scrollHeight = (clipHeight / _totalHeight) * clipHeight;
  674. _scrollBarBounds.set(((-_scrollPosition.x) / _totalWidth) * clipWidth,
  675. ((-_scrollPosition.y) / _totalHeight) * clipHeight,
  676. scrollWidth, scrollHeight);
  677. // If scroll velocity is 0 and scrollbars are not always visible, trigger fade-out animation.
  678. if (!_scrolling && _scrollingVelocity.isZero() && _scrollBarsAutoHide && _scrollBarOpacity == 1.0f)
  679. {
  680. float to = 0;
  681. _scrollBarOpacity = 0.99f;
  682. if (!_scrollBarOpacityClip)
  683. {
  684. Animation* animation = createAnimationFromTo("scrollbar-fade-out", ANIMATE_OPACITY, &_scrollBarOpacity, &to, Curve::QUADRATIC_IN_OUT, 500L);
  685. _scrollBarOpacityClip = animation->getClip();
  686. }
  687. _scrollBarOpacityClip->play();
  688. }
  689. // Position controls within scroll area.
  690. _layout->update(this, _scrollPosition);
  691. }
  692. bool Container::touchEventScroll(Touch::TouchEvent evt, int x, int y, unsigned int contactIndex)
  693. {
  694. switch(evt)
  695. {
  696. case Touch::TOUCH_PRESS:
  697. if (_contactIndex == INVALID_CONTACT_INDEX)
  698. {
  699. _contactIndex = (int) contactIndex;
  700. _contactIndices++;
  701. _scrollingLastX = _scrollingFirstX = _scrollingVeryFirstX = x;
  702. _scrollingLastY = _scrollingFirstY = _scrollingVeryFirstY = y;
  703. _scrollingVelocity.set(0, 0);
  704. _scrolling = true;
  705. _scrollingStartTimeX = _scrollingStartTimeY = 0;
  706. if (_scrollBarOpacityClip && _scrollBarOpacityClip->isPlaying())
  707. {
  708. _scrollBarOpacityClip->stop();
  709. _scrollBarOpacityClip = NULL;
  710. }
  711. _scrollBarOpacity = 1.0f;
  712. _dirty = true;
  713. return _consumeInputEvents;
  714. }
  715. break;
  716. case Touch::TOUCH_MOVE:
  717. if (_scrolling && _contactIndex == (int) contactIndex)
  718. {
  719. double gameTime = Game::getAbsoluteTime();
  720. // Calculate the latest movement delta for the next update to use.
  721. int vx = x - _scrollingLastX;
  722. int vy = y - _scrollingLastY;
  723. if (_scrollingMouseVertically)
  724. {
  725. float yRatio = _totalHeight / _absoluteBounds.height;
  726. vy *= yRatio;
  727. _scrollingVelocity.set(0, -vy);
  728. _scrollPosition.y -= vy;
  729. }
  730. else if (_scrollingMouseHorizontally)
  731. {
  732. float xRatio = _totalWidth / _absoluteBounds.width;
  733. vx *= xRatio;
  734. _scrollingVelocity.set(-vx, 0);
  735. _scrollPosition.x -= vx;
  736. }
  737. else
  738. {
  739. _scrollingVelocity.set(vx, vy);
  740. _scrollPosition.x += vx;
  741. _scrollPosition.y += vy;
  742. }
  743. _scrollingLastX = x;
  744. _scrollingLastY = y;
  745. // If the user changes direction, reset the start time and position.
  746. bool goingRight = (vx > 0);
  747. if (goingRight != _scrollingRight)
  748. {
  749. _scrollingFirstX = x;
  750. _scrollingRight = goingRight;
  751. _scrollingStartTimeX = gameTime;
  752. }
  753. bool goingDown = (vy > 0);
  754. if (goingDown != _scrollingDown)
  755. {
  756. _scrollingFirstY = y;
  757. _scrollingDown = goingDown;
  758. _scrollingStartTimeY = gameTime;
  759. }
  760. if (!_scrollingStartTimeX)
  761. _scrollingStartTimeX = gameTime;
  762. if (!_scrollingStartTimeY)
  763. _scrollingStartTimeY = gameTime;
  764. _scrollingLastTime = gameTime;
  765. _dirty = true;
  766. return _consumeInputEvents;
  767. }
  768. break;
  769. case Touch::TOUCH_RELEASE:
  770. if (_contactIndex == (int) contactIndex)
  771. {
  772. _contactIndex = INVALID_CONTACT_INDEX;
  773. _contactIndices--;
  774. _scrolling = false;
  775. double gameTime = Game::getAbsoluteTime();
  776. float timeSinceLastMove = (float)(gameTime - _scrollingLastTime);
  777. if (timeSinceLastMove > SCROLL_INERTIA_DELAY)
  778. {
  779. _scrollingVelocity.set(0, 0);
  780. _scrollingMouseVertically = _scrollingMouseHorizontally = false;
  781. _dirty = true;
  782. return _consumeInputEvents;
  783. }
  784. int dx = _scrollingLastX - _scrollingFirstX;
  785. int dy = _scrollingLastY - _scrollingFirstY;
  786. float timeTakenX = (float)(gameTime - _scrollingStartTimeX);
  787. float elapsedSecsX = timeTakenX * 0.001f;
  788. float timeTakenY = (float)(gameTime - _scrollingStartTimeY);
  789. float elapsedSecsY = timeTakenY * 0.001f;
  790. float vx = dx;
  791. float vy = dy;
  792. if (elapsedSecsX > 0)
  793. vx = (float)dx / elapsedSecsX;
  794. if (elapsedSecsY > 0)
  795. vy = (float)dy / elapsedSecsY;
  796. if (_scrollingMouseVertically)
  797. {
  798. float yRatio = _totalHeight / _absoluteBounds.height;
  799. vy *= yRatio;
  800. _scrollingVelocity.set(0, -vy);
  801. }
  802. else if (_scrollingMouseHorizontally)
  803. {
  804. float xRatio = _totalWidth / _absoluteBounds.width;
  805. vx *= xRatio;
  806. _scrollingVelocity.set(-vx, 0);
  807. }
  808. else
  809. {
  810. _scrollingVelocity.set(vx, vy);
  811. }
  812. _scrollingMouseVertically = _scrollingMouseHorizontally = false;
  813. _dirty = true;
  814. return _consumeInputEvents;
  815. }
  816. break;
  817. }
  818. return false;
  819. }
  820. bool Container::mouseEventScroll(Mouse::MouseEvent evt, int x, int y, int wheelDelta)
  821. {
  822. switch(evt)
  823. {
  824. case Mouse::MOUSE_PRESS_LEFT_BUTTON:
  825. {
  826. if (_scrollBarVertical)
  827. {
  828. float vWidth = _scrollBarVertical->getRegion().width;
  829. Rectangle vBounds(_viewportBounds.x + _viewportBounds.width - vWidth,
  830. _scrollBarBounds.y,
  831. vWidth, _scrollBarBounds.height);
  832. if (x + _viewportBounds.x >= vBounds.x &&
  833. x + _viewportBounds.x <= vBounds.x + vBounds.width)
  834. {
  835. // Then we're within the horizontal bounds of the vertical scrollbar.
  836. // We want to either jump up or down, or drag the scrollbar itself.
  837. if (y < vBounds.y)
  838. {
  839. _scrollPosition.y += _totalHeight / 5.0f;
  840. }
  841. else if (y > vBounds.y + vBounds.height)
  842. {
  843. _scrollPosition.y -= _totalHeight / 5.0f;
  844. }
  845. else
  846. {
  847. _scrollingMouseVertically = true;
  848. }
  849. }
  850. }
  851. if (_scrollBarHorizontal)
  852. {
  853. float hHeight = _scrollBarHorizontal->getRegion().height;
  854. Rectangle hBounds(_scrollBarBounds.x,
  855. _viewportBounds.y + _viewportBounds.height - hHeight,
  856. _scrollBarBounds.width, hHeight);
  857. if (y + _viewportBounds.y >= hBounds.y &&
  858. y + _viewportBounds.y <= hBounds.y + hBounds.height)
  859. {
  860. // We're within the vertical bounds of the horizontal scrollbar.
  861. if (x < hBounds.x)
  862. _scrollPosition.x += _totalWidth / 5.0f;
  863. else if (x > hBounds.x + hBounds.width)
  864. _scrollPosition.x -= _totalWidth / 5.0f;
  865. else
  866. _scrollingMouseHorizontally = true;
  867. }
  868. }
  869. return touchEventScroll(Touch::TOUCH_PRESS, x, y, 0);
  870. }
  871. case Mouse::MOUSE_MOVE:
  872. return touchEventScroll(Touch::TOUCH_MOVE, x, y, 0);
  873. case Mouse::MOUSE_RELEASE_LEFT_BUTTON:
  874. return touchEventScroll(Touch::TOUCH_RELEASE, x, y, 0);
  875. case Mouse::MOUSE_WHEEL:
  876. _scrollPosition.y += (_totalHeight / 10.0f) * wheelDelta;
  877. if (_scrollBarOpacityClip && _scrollBarOpacityClip->isPlaying())
  878. {
  879. _scrollBarOpacityClip->stop();
  880. _scrollBarOpacityClip = NULL;
  881. }
  882. _scrollBarOpacity = 1.0f;
  883. _dirty = true;
  884. return _consumeInputEvents;
  885. }
  886. return false;
  887. }
  888. bool Container::pointerEvent(bool mouse, char evt, int x, int y, int data)
  889. {
  890. if (!isEnabled() || !isVisible())
  891. {
  892. return false;
  893. }
  894. // This event may run untrusted code by notifying listeners of events.
  895. // If the user calls exit() or otherwise releases this container, we
  896. // need to keep it alive until the method returns.
  897. addRef();
  898. bool eventConsumed = false;
  899. const Theme::Border& border = getBorder(_state);
  900. const Theme::Padding& padding = getPadding();
  901. float xPos = border.left + padding.left;
  902. float yPos = border.top + padding.top;
  903. Vector2* offset = NULL;
  904. if (_scroll != SCROLL_NONE)
  905. {
  906. offset = &_scrollPosition;
  907. }
  908. std::vector<Control*>::const_iterator it;
  909. for (it = _controls.begin(); it < _controls.end(); it++)
  910. {
  911. Control* control = *it;
  912. GP_ASSERT(control);
  913. if (!control->isEnabled() || !control->isVisible())
  914. {
  915. continue;
  916. }
  917. const Rectangle& bounds = control->getBounds();
  918. float boundsX = bounds.x;
  919. float boundsY = bounds.y;
  920. if (offset)
  921. {
  922. boundsX += offset->x;
  923. boundsY += offset->y;
  924. }
  925. Control::State currentState = control->getState();
  926. if ((control->isContainer() && currentState == Control::FOCUS) ||
  927. (currentState != Control::NORMAL) ||
  928. ((evt == Touch::TOUCH_PRESS ||
  929. evt == Mouse::MOUSE_PRESS_LEFT_BUTTON ||
  930. evt == Mouse::MOUSE_PRESS_MIDDLE_BUTTON ||
  931. evt == Mouse::MOUSE_PRESS_RIGHT_BUTTON) &&
  932. x >= xPos + boundsX &&
  933. x <= xPos + boundsX + bounds.width &&
  934. y >= yPos + boundsY &&
  935. y <= yPos + boundsY + bounds.height))
  936. {
  937. // Pass on the event's clip relative to the control.
  938. if (mouse)
  939. eventConsumed |= control->mouseEvent((Mouse::MouseEvent)evt, x - xPos - boundsX, y - yPos - boundsY, data);
  940. else
  941. eventConsumed |= control->touchEvent((Touch::TouchEvent)evt, x - xPos - boundsX, y - yPos - boundsY, (unsigned int)data);
  942. }
  943. }
  944. if (!isEnabled() || !isVisible())
  945. {
  946. release();
  947. return (_consumeInputEvents | eventConsumed);
  948. }
  949. bool withinClipBounds = false;
  950. switch (evt)
  951. {
  952. case Touch::TOUCH_PRESS:
  953. if (x > _clipBounds.x && x <= _clipBounds.x + _clipBounds.width &&
  954. y > _clipBounds.y && y <= _clipBounds.y + _clipBounds.height)
  955. {
  956. setState(Control::FOCUS);
  957. withinClipBounds = true;
  958. if (eventConsumed)
  959. _contactIndices++;
  960. }
  961. else if (_contactIndices == 0)
  962. {
  963. setState(Control::NORMAL);
  964. _contactIndex = INVALID_CONTACT_INDEX;
  965. release();
  966. return false;
  967. }
  968. break;
  969. case Touch::TOUCH_RELEASE:
  970. if (eventConsumed)
  971. {
  972. if (_contactIndices > 0)
  973. _contactIndices--;
  974. }
  975. break;
  976. }
  977. if (!eventConsumed && _scroll != SCROLL_NONE && getState() == Control::FOCUS && (evt != Touch::TOUCH_PRESS || withinClipBounds))
  978. {
  979. if ((mouse && mouseEventScroll((Mouse::MouseEvent)evt, x - xPos, y - yPos, data)) ||
  980. (!mouse && touchEventScroll((Touch::TouchEvent)evt, x - xPos, y - yPos, (unsigned int)data)))
  981. {
  982. eventConsumed = true;
  983. }
  984. }
  985. release();
  986. if (x > _clipBounds.x && x <= _clipBounds.x + _clipBounds.width &&
  987. y > _clipBounds.y && y <= _clipBounds.y + _clipBounds.height)
  988. return (_consumeInputEvents | eventConsumed);
  989. else
  990. return eventConsumed;
  991. }
  992. Container::Scroll Container::getScroll(const char* scroll)
  993. {
  994. if (!scroll)
  995. return Container::SCROLL_NONE;
  996. if (strcmp(scroll, "SCROLL_NONE") == 0)
  997. {
  998. return Container::SCROLL_NONE;
  999. }
  1000. else if (strcmp(scroll, "SCROLL_HORIZONTAL") == 0)
  1001. {
  1002. return Container::SCROLL_HORIZONTAL;
  1003. }
  1004. else if (strcmp(scroll, "SCROLL_VERTICAL") == 0)
  1005. {
  1006. return Container::SCROLL_VERTICAL;
  1007. }
  1008. else if (strcmp(scroll, "SCROLL_BOTH") == 0)
  1009. {
  1010. return Container::SCROLL_BOTH;
  1011. }
  1012. else
  1013. {
  1014. GP_ERROR("Failed to get corresponding scroll state for unsupported value '%s'.", scroll);
  1015. }
  1016. return Container::SCROLL_NONE;
  1017. }
  1018. static bool sortControlsByZOrder(Control* c1, Control* c2)
  1019. {
  1020. if (c1->getZIndex() < c2->getZIndex())
  1021. return true;
  1022. return false;
  1023. }
  1024. unsigned int Container::getAnimationPropertyComponentCount(int propertyId) const
  1025. {
  1026. switch(propertyId)
  1027. {
  1028. case ANIMATE_OPACITY:
  1029. return 1;
  1030. default:
  1031. return Control::getAnimationPropertyComponentCount(propertyId);
  1032. }
  1033. }
  1034. void Container::getAnimationPropertyValue(int propertyId, AnimationValue* value)
  1035. {
  1036. GP_ASSERT(value);
  1037. switch(propertyId)
  1038. {
  1039. case ANIMATE_OPACITY:
  1040. value->setFloat(0, _scrollBarOpacity);
  1041. break;
  1042. default:
  1043. Control::getAnimationPropertyValue(propertyId, value);
  1044. break;
  1045. }
  1046. }
  1047. void Container::setAnimationPropertyValue(int propertyId, AnimationValue* value, float blendWeight)
  1048. {
  1049. GP_ASSERT(value);
  1050. switch(propertyId)
  1051. {
  1052. case ANIMATE_OPACITY:
  1053. _scrollBarOpacity = Curve::lerp(blendWeight, _opacity, value->getFloat(0));
  1054. _dirty = true;
  1055. break;
  1056. default:
  1057. Control::setAnimationPropertyValue(propertyId, value, blendWeight);
  1058. break;
  1059. }
  1060. }
  1061. }