Buttons.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. /*
  2. * Buttons.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "Buttons.h"
  12. #include "Images.h"
  13. #include "TextControls.h"
  14. #include "../CGameInfo.h"
  15. #include "../CPlayerInterface.h"
  16. #include "../battle/BattleInterface.h"
  17. #include "../battle/BattleInterfaceClasses.h"
  18. #include "../eventsSDL/InputHandler.h"
  19. #include "../gui/CGuiHandler.h"
  20. #include "../gui/MouseButton.h"
  21. #include "../gui/Shortcut.h"
  22. #include "../gui/InterfaceObjectConfigurable.h"
  23. #include "../media/ISoundPlayer.h"
  24. #include "../windows/InfoWindows.h"
  25. #include "../render/CAnimation.h"
  26. #include "../render/Canvas.h"
  27. #include "../render/IRenderHandler.h"
  28. #include "../../lib/CConfigHandler.h"
  29. #include "../../lib/CGeneralTextHandler.h"
  30. #include "../../lib/filesystem/Filesystem.h"
  31. void ButtonBase::update()
  32. {
  33. if (overlay)
  34. {
  35. Point targetPos = Rect::createCentered( pos, overlay->pos.dimensions()).topLeft();
  36. if (state == EButtonState::PRESSED)
  37. overlay->moveTo(targetPos + Point(1,1));
  38. else
  39. overlay->moveTo(targetPos);
  40. }
  41. if (image)
  42. {
  43. // checkbox - has only have two frames: normal and pressed/highlighted
  44. // hero movement speed buttons: only three frames: normal, pressed and blocked/highlighted
  45. if (state == EButtonState::HIGHLIGHTED && image->size() < 4)
  46. image->setFrame(image->size()-1);
  47. image->setFrame(stateToIndex[vstd::to_underlying(state)]);
  48. }
  49. if (isActive())
  50. redraw();
  51. }
  52. void CButton::setBorderColor(std::optional<ColorRGBA> newBorderColor)
  53. {
  54. borderColor = newBorderColor;
  55. }
  56. void CButton::addCallback(const std::function<void()> & callback)
  57. {
  58. this->callback += callback;
  59. }
  60. void CButton::addPopupCallback(const std::function<void()> & callback)
  61. {
  62. this->callbackPopup += callback;
  63. }
  64. void CButton::addHoverCallback(const std::function<void(bool)> & callback)
  65. {
  66. this->hoverCallback += callback;
  67. }
  68. void CButton::addPanningCallback(const std::function<void(const Point &, const Point &, const Point &)> & callback)
  69. {
  70. this->panningCallback += callback;
  71. }
  72. void ButtonBase::setTextOverlay(const std::string & Text, EFonts font, ColorRGBA color)
  73. {
  74. OBJECT_CONSTRUCTION_CUSTOM_CAPTURING(255-DISPOSE);
  75. setOverlay(std::make_shared<CLabel>(pos.w/2, pos.h/2, font, ETextAlignment::CENTER, color, Text));
  76. update();
  77. }
  78. void ButtonBase::setOverlay(const std::shared_ptr<CIntObject>& newOverlay)
  79. {
  80. overlay = newOverlay;
  81. if(overlay)
  82. {
  83. addChild(newOverlay.get());
  84. Point targetPos = Rect::createCentered( pos, overlay->pos.dimensions()).topLeft();
  85. overlay->moveTo(targetPos);
  86. }
  87. update();
  88. }
  89. void ButtonBase::setImage(const AnimationPath & defName, bool playerColoredButton)
  90. {
  91. OBJECT_CONSTRUCTION_CUSTOM_CAPTURING(255-DISPOSE);
  92. configurable.reset();
  93. image = std::make_shared<CAnimImage>(defName, vstd::to_underlying(getState()));
  94. pos = image->pos;
  95. if (playerColoredButton)
  96. image->playerColored(LOCPLINT->playerID);
  97. }
  98. const JsonNode & ButtonBase::getCurrentConfig() const
  99. {
  100. if (!config)
  101. throw std::runtime_error("No config found in button!");
  102. static constexpr std::array stateToConfig = {
  103. "normal",
  104. "pressed",
  105. "blocked",
  106. "highlighted"
  107. };
  108. std::string key = stateToConfig[vstd::to_underlying(getState())];
  109. const JsonNode & value = (*config)[key];
  110. if (value.isNull())
  111. throw std::runtime_error("No config found in button for state " + key + "!");
  112. return value;
  113. }
  114. void ButtonBase::setConfigurable(const JsonPath & jsonName, bool playerColoredButton)
  115. {
  116. OBJECT_CONSTRUCTION_CUSTOM_CAPTURING(255-DISPOSE);
  117. config = std::make_unique<JsonNode>(jsonName);
  118. image.reset();
  119. configurable = std::make_shared<InterfaceObjectConfigurable>(getCurrentConfig());
  120. pos = configurable->pos;
  121. if (playerColoredButton)
  122. image->playerColored(LOCPLINT->playerID);
  123. }
  124. void CButton::addHoverText(EButtonState state, const std::string & text)
  125. {
  126. hoverTexts[vstd::to_underlying(state)] = text;
  127. }
  128. void ButtonBase::setImageOrder(int state1, int state2, int state3, int state4)
  129. {
  130. stateToIndex[0] = state1;
  131. stateToIndex[1] = state2;
  132. stateToIndex[2] = state3;
  133. stateToIndex[3] = state4;
  134. update();
  135. }
  136. std::shared_ptr<CIntObject> ButtonBase::getOverlay()
  137. {
  138. return overlay;
  139. }
  140. void ButtonBase::setStateImpl(EButtonState newState)
  141. {
  142. state = newState;
  143. if (configurable)
  144. {
  145. OBJECT_CONSTRUCTION_CUSTOM_CAPTURING(255-DISPOSE);
  146. configurable = std::make_shared<InterfaceObjectConfigurable>(getCurrentConfig());
  147. pos = configurable->pos;
  148. if (overlay)
  149. {
  150. // Force overlay on top
  151. removeChild(overlay.get());
  152. addChild(overlay.get());
  153. }
  154. }
  155. update();
  156. }
  157. void CButton::setState(EButtonState newState)
  158. {
  159. if (getState() == newState)
  160. return;
  161. if (newState == EButtonState::BLOCKED)
  162. removeUsedEvents(LCLICK | SHOW_POPUP | HOVER | KEYBOARD);
  163. else
  164. addUsedEvents(LCLICK | SHOW_POPUP | HOVER | KEYBOARD);
  165. setStateImpl(newState);
  166. }
  167. EButtonState ButtonBase::getState() const
  168. {
  169. return state;
  170. }
  171. bool CButton::isBlocked()
  172. {
  173. return getState() == EButtonState::BLOCKED;
  174. }
  175. bool CButton::isHighlighted()
  176. {
  177. return getState() == EButtonState::HIGHLIGHTED;
  178. }
  179. void CButton::setHoverable(bool on)
  180. {
  181. hoverable = on;
  182. }
  183. void CButton::setSoundDisabled(bool on)
  184. {
  185. soundDisabled = on;
  186. }
  187. void CButton::setActOnDown(bool on)
  188. {
  189. actOnDown = on;
  190. }
  191. void CButton::setHelp(const std::pair<std::string, std::string> & help)
  192. {
  193. hoverTexts[0] = help.first;
  194. helpBox = help.second;
  195. }
  196. void CButton::block(bool on)
  197. {
  198. if(on || getState() == EButtonState::BLOCKED) //dont change button state if unblock requested, but it's not blocked
  199. setState(on ? EButtonState::BLOCKED : EButtonState::NORMAL);
  200. }
  201. void CButton::onButtonClicked()
  202. {
  203. // debug logging to figure out pressed button (and as result - player actions) in case of crash
  204. logAnim->trace("Button clicked at %dx%d", pos.x, pos.y);
  205. CIntObject * parent = this->parent;
  206. std::string prefix = "Parent is";
  207. while (parent)
  208. {
  209. logAnim->trace("%s%s at %dx%d", prefix, typeid(*parent).name(), parent->pos.x, parent->pos.y);
  210. parent = parent->parent;
  211. prefix = '\t' + prefix;
  212. }
  213. callback();
  214. }
  215. void CButton::clickPressed(const Point & cursorPosition)
  216. {
  217. if(isBlocked())
  218. return;
  219. if (getState() != EButtonState::PRESSED)
  220. {
  221. if (!soundDisabled)
  222. {
  223. CCS->soundh->playSound(soundBase::button);
  224. GH.input().hapticFeedback();
  225. }
  226. setState(EButtonState::PRESSED);
  227. if (actOnDown)
  228. onButtonClicked();
  229. }
  230. }
  231. void CButton::clickReleased(const Point & cursorPosition)
  232. {
  233. if (getState() == EButtonState::PRESSED)
  234. {
  235. if(hoverable && isHovered())
  236. setState(EButtonState::HIGHLIGHTED);
  237. else
  238. setState(EButtonState::NORMAL);
  239. if (!actOnDown)
  240. onButtonClicked();
  241. }
  242. }
  243. void CButton::clickCancel(const Point & cursorPosition)
  244. {
  245. if (getState() == EButtonState::PRESSED)
  246. {
  247. if(hoverable && isHovered())
  248. setState(EButtonState::HIGHLIGHTED);
  249. else
  250. setState(EButtonState::NORMAL);
  251. }
  252. }
  253. void CButton::showPopupWindow(const Point & cursorPosition)
  254. {
  255. callbackPopup();
  256. if(!helpBox.empty()) //there is no point to show window with nothing inside...
  257. CRClickPopup::createAndPush(helpBox);
  258. }
  259. void CButton::hover (bool on)
  260. {
  261. hoverCallback(on);
  262. if(hoverable && !isBlocked())
  263. {
  264. if(on)
  265. setState(EButtonState::HIGHLIGHTED);
  266. else
  267. setState(EButtonState::NORMAL);
  268. }
  269. /*if(pressedL && on) // WTF is this? When this is used?
  270. setState(PRESSED);*/
  271. std::string name = hoverTexts[vstd::to_underlying(getState())].empty()
  272. ? hoverTexts[0]
  273. : hoverTexts[vstd::to_underlying(getState())];
  274. if(!name.empty() && !isBlocked()) //if there is no name, there is nothing to display also
  275. {
  276. if (on)
  277. GH.statusbar()->write(name);
  278. else
  279. GH.statusbar()->clearIfMatching(name);
  280. }
  281. }
  282. void CButton::gesturePanning(const Point & initialPosition, const Point & currentPosition, const Point & lastUpdateDistance)
  283. {
  284. panningCallback(initialPosition, currentPosition, lastUpdateDistance);
  285. }
  286. ButtonBase::ButtonBase(Point position, const AnimationPath & defName, EShortcut key, bool playerColoredButton)
  287. : CKeyShortcut(key)
  288. , stateToIndex({0, 1, 2, 3})
  289. , state(EButtonState::NORMAL)
  290. {
  291. pos.x += position.x;
  292. pos.y += position.y;
  293. JsonPath jsonConfig = defName.toType<EResType::JSON>().addPrefix("CONFIG/WIDGETS/BUTTONS/");
  294. if (CResourceHandler::get()->existsResource(jsonConfig))
  295. {
  296. setConfigurable(jsonConfig, playerColoredButton);
  297. return;
  298. }
  299. else
  300. {
  301. setImage(defName, playerColoredButton);
  302. return;
  303. }
  304. }
  305. ButtonBase::~ButtonBase() = default;
  306. CButton::CButton(Point position, const AnimationPath &defName, const std::pair<std::string, std::string> &help, CFunctionList<void()> Callback, EShortcut key, bool playerColoredButton):
  307. ButtonBase(position, defName, key, playerColoredButton),
  308. callback(Callback),
  309. helpBox(help.second),
  310. actOnDown(false),
  311. hoverable(false),
  312. soundDisabled(false)
  313. {
  314. defActions = 255-DISPOSE;
  315. addUsedEvents(LCLICK | SHOW_POPUP | HOVER | KEYBOARD | GESTURE);
  316. hoverTexts[0] = help.first;
  317. }
  318. void ButtonBase::setPlayerColor(PlayerColor player)
  319. {
  320. if (image && image->isPlayerColored())
  321. image->playerColored(player);
  322. }
  323. void CButton::showAll(Canvas & to)
  324. {
  325. CIntObject::showAll(to);
  326. if (borderColor)
  327. to.drawBorder(Rect::createAround(pos, 1), *borderColor);
  328. }
  329. std::pair<std::string, std::string> CButton::tooltip()
  330. {
  331. return std::pair<std::string, std::string>();
  332. }
  333. std::pair<std::string, std::string> CButton::tooltipLocalized(const std::string & key)
  334. {
  335. return std::make_pair(
  336. CGI->generaltexth->translate(key, "hover"),
  337. CGI->generaltexth->translate(key, "help")
  338. );
  339. }
  340. std::pair<std::string, std::string> CButton::tooltip(const std::string & hover, const std::string & help)
  341. {
  342. return std::make_pair(hover, help);
  343. }
  344. CToggleBase::CToggleBase(CFunctionList<void (bool)> callback):
  345. callback(callback),
  346. selected(false),
  347. allowDeselection(true)
  348. {
  349. }
  350. CToggleBase::~CToggleBase() = default;
  351. void CToggleBase::doSelect(bool on)
  352. {
  353. // for overrides
  354. }
  355. void CToggleBase::setEnabled(bool enabled)
  356. {
  357. // for overrides
  358. }
  359. void CToggleBase::setSelectedSilent(bool on)
  360. {
  361. selected = on;
  362. doSelect(on);
  363. }
  364. void CToggleBase::setSelected(bool on)
  365. {
  366. bool changed = (on != selected);
  367. setSelectedSilent(on);
  368. if (changed)
  369. callback(on);
  370. }
  371. bool CToggleBase::isSelected() const
  372. {
  373. return selected;
  374. }
  375. bool CToggleBase::canActivate() const
  376. {
  377. return !selected || allowDeselection;
  378. }
  379. void CToggleBase::addCallback(const std::function<void(bool)> & function)
  380. {
  381. callback += function;
  382. }
  383. void CToggleBase::setAllowDeselection(bool on)
  384. {
  385. allowDeselection = on;
  386. }
  387. CToggleButton::CToggleButton(Point position, const AnimationPath &defName, const std::pair<std::string, std::string> &help,
  388. CFunctionList<void(bool)> callback, EShortcut key, bool playerColoredButton):
  389. CButton(position, defName, help, 0, key, playerColoredButton),
  390. CToggleBase(callback)
  391. {
  392. }
  393. void CToggleButton::doSelect(bool on)
  394. {
  395. if (on)
  396. {
  397. setState(EButtonState::HIGHLIGHTED);
  398. }
  399. else
  400. {
  401. setState(EButtonState::NORMAL);
  402. }
  403. }
  404. void CToggleButton::setEnabled(bool enabled)
  405. {
  406. setState(enabled ? EButtonState::NORMAL : EButtonState::BLOCKED);
  407. }
  408. void CToggleButton::clickPressed(const Point & cursorPosition)
  409. {
  410. // force refresh
  411. hover(false);
  412. hover(true);
  413. if(isBlocked())
  414. return;
  415. if (canActivate())
  416. {
  417. CCS->soundh->playSound(soundBase::button);
  418. GH.input().hapticFeedback();
  419. setState(EButtonState::PRESSED);
  420. }
  421. }
  422. void CToggleButton::clickReleased(const Point & cursorPosition)
  423. {
  424. // force refresh
  425. hover(false);
  426. hover(true);
  427. if(isBlocked())
  428. return;
  429. if (getState() == EButtonState::PRESSED && canActivate())
  430. {
  431. onButtonClicked();
  432. setSelected(!isSelected());
  433. }
  434. else
  435. doSelect(isSelected()); // restore
  436. }
  437. void CToggleButton::clickCancel(const Point & cursorPosition)
  438. {
  439. // force refresh
  440. hover(false);
  441. hover(true);
  442. if(isBlocked())
  443. return;
  444. doSelect(isSelected());
  445. }
  446. void CToggleGroup::addCallback(const std::function<void(int)> & callback)
  447. {
  448. onChange += callback;
  449. }
  450. void CToggleGroup::resetCallback()
  451. {
  452. onChange.clear();
  453. }
  454. void CToggleGroup::addToggle(int identifier, const std::shared_ptr<CToggleBase> & button)
  455. {
  456. if(auto intObj = std::dynamic_pointer_cast<CIntObject>(button)) // hack-ish workagound to avoid diamond problem with inheritance
  457. {
  458. addChild(intObj.get());
  459. }
  460. button->addCallback([=] (bool on) { if (on) selectionChanged(identifier);});
  461. button->setAllowDeselection(false);
  462. if(buttons.count(identifier)>0)
  463. logAnim->error("Duplicated toggle button id %d", identifier);
  464. buttons[identifier] = button;
  465. }
  466. CToggleGroup::CToggleGroup(const CFunctionList<void(int)> &OnChange)
  467. : onChange(OnChange), selectedID(-2)
  468. {
  469. }
  470. void CToggleGroup::setSelected(int id)
  471. {
  472. selectionChanged(id);
  473. }
  474. void CToggleGroup::setSelectedOnly(int id)
  475. {
  476. for(const auto & button : buttons)
  477. button.second->setEnabled(button.first == id);
  478. selectionChanged(id);
  479. }
  480. void CToggleGroup::selectionChanged(int to)
  481. {
  482. if (to == selectedID)
  483. return;
  484. int oldSelection = selectedID;
  485. selectedID = to;
  486. if (buttons.count(oldSelection))
  487. buttons[oldSelection]->setSelected(false);
  488. if (buttons.count(to))
  489. buttons[to]->setSelected(true);
  490. onChange(to);
  491. redraw();
  492. }
  493. int CToggleGroup::getSelected() const
  494. {
  495. return selectedID;
  496. }