Buttons.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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 "../CPlayerInterface.h"
  15. #include "../battle/BattleInterface.h"
  16. #include "../eventsSDL/InputHandler.h"
  17. #include "../GameEngine.h"
  18. #include "../GameInstance.h"
  19. #include "../gui/MouseButton.h"
  20. #include "../gui/Shortcut.h"
  21. #include "../gui/InterfaceObjectConfigurable.h"
  22. #include "../media/ISoundPlayer.h"
  23. #include "../windows/InfoWindows.h"
  24. #include "../render/Canvas.h"
  25. #include "../render/IRenderHandler.h"
  26. #include "../../lib/CConfigHandler.h"
  27. #include "../../lib/texts/CGeneralTextHandler.h"
  28. #include "../../lib/filesystem/Filesystem.h"
  29. #include "../../lib/GameLibrary.h"
  30. void ButtonBase::update()
  31. {
  32. if (overlay)
  33. {
  34. Point targetPos = Rect::createCentered( pos, overlay->pos.dimensions()).topLeft();
  35. if (state == EButtonState::PRESSED)
  36. overlay->moveTo(targetPos + Point(1,1));
  37. else
  38. overlay->moveTo(targetPos);
  39. }
  40. if (image)
  41. {
  42. // checkbox - has only have two frames: normal and pressed/highlighted
  43. // hero movement speed buttons: only three frames: normal, pressed and blocked/highlighted
  44. if (state == EButtonState::HIGHLIGHTED && image->size() < 4)
  45. image->setFrame(image->size()-1);
  46. else
  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::setHighlightedBorderColor(std::optional<ColorRGBA> newBorderColor)
  57. {
  58. highlightedBorderColor = newBorderColor;
  59. }
  60. void CButton::addCallback(const std::function<void()> & callback)
  61. {
  62. this->callback += callback;
  63. }
  64. void CButton::addPopupCallback(const std::function<void()> & callback)
  65. {
  66. this->callbackPopup += callback;
  67. }
  68. void ButtonBase::setTextOverlay(const std::string & Text, EFonts font, ColorRGBA color)
  69. {
  70. OBJECT_CONSTRUCTION;
  71. setOverlay(std::make_shared<CLabel>(pos.w/2, pos.h/2, font, ETextAlignment::CENTER, color, Text));
  72. update();
  73. }
  74. void ButtonBase::setOverlay(const std::shared_ptr<CIntObject>& newOverlay)
  75. {
  76. overlay = newOverlay;
  77. if(overlay)
  78. {
  79. addChild(newOverlay.get());
  80. Point targetPos = Rect::createCentered( pos, overlay->pos.dimensions()).topLeft();
  81. overlay->moveTo(targetPos);
  82. }
  83. update();
  84. }
  85. void ButtonBase::setImage(const AnimationPath & defName, bool playerColoredButton)
  86. {
  87. OBJECT_CONSTRUCTION;
  88. configurable.reset();
  89. image = std::make_shared<CAnimImage>(defName, vstd::to_underlying(getState()));
  90. pos = image->pos;
  91. if (playerColoredButton)
  92. image->setPlayerColor(GAME->interface()->playerID);
  93. }
  94. const JsonNode & ButtonBase::getCurrentConfig() const
  95. {
  96. if (!config)
  97. throw std::runtime_error("No config found in button!");
  98. static constexpr std::array stateToConfig = {
  99. "normal",
  100. "pressed",
  101. "blocked",
  102. "highlighted"
  103. };
  104. std::string key = stateToConfig[vstd::to_underlying(getState())];
  105. const JsonNode & value = (*config)[key];
  106. if (value.isNull())
  107. throw std::runtime_error("No config found in button for state " + key + "!");
  108. return value;
  109. }
  110. void ButtonBase::setConfigurable(const JsonPath & jsonName, bool playerColoredButton)
  111. {
  112. OBJECT_CONSTRUCTION;
  113. config = std::make_unique<JsonNode>(jsonName);
  114. image.reset();
  115. configurable = std::make_shared<InterfaceObjectConfigurable>(getCurrentConfig());
  116. pos = configurable->pos;
  117. if (playerColoredButton)
  118. image->setPlayerColor(GAME->interface()->playerID);
  119. }
  120. void CButton::addHoverText(EButtonState state, const std::string & text)
  121. {
  122. hoverTexts[vstd::to_underlying(state)] = text;
  123. }
  124. void ButtonBase::setImageOrder(int state1, int state2, int state3, int state4)
  125. {
  126. stateToIndex[0] = state1;
  127. stateToIndex[1] = state2;
  128. stateToIndex[2] = state3;
  129. stateToIndex[3] = state4;
  130. update();
  131. }
  132. std::shared_ptr<CIntObject> ButtonBase::getOverlay()
  133. {
  134. return overlay;
  135. }
  136. void ButtonBase::setStateImpl(EButtonState newState)
  137. {
  138. state = newState;
  139. if (configurable)
  140. {
  141. OBJECT_CONSTRUCTION;
  142. configurable = std::make_shared<InterfaceObjectConfigurable>(getCurrentConfig());
  143. pos = configurable->pos;
  144. if (overlay)
  145. {
  146. // Force overlay on top
  147. removeChild(overlay.get());
  148. addChild(overlay.get());
  149. }
  150. }
  151. update();
  152. }
  153. void CButton::setState(EButtonState newState)
  154. {
  155. if (getState() == newState)
  156. return;
  157. if (newState == EButtonState::BLOCKED)
  158. removeUsedEvents(LCLICK | SHOW_POPUP | HOVER | KEYBOARD);
  159. else
  160. addUsedEvents(LCLICK | SHOW_POPUP | HOVER | KEYBOARD);
  161. setStateImpl(newState);
  162. }
  163. EButtonState ButtonBase::getState() const
  164. {
  165. return state;
  166. }
  167. bool CButton::isBlocked()
  168. {
  169. return getState() == EButtonState::BLOCKED;
  170. }
  171. bool CButton::isHighlighted()
  172. {
  173. return getState() == EButtonState::HIGHLIGHTED;
  174. }
  175. bool CButton::isPressed()
  176. {
  177. return getState() == EButtonState::PRESSED;
  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. ENGINE->sound().playSound(soundBase::button);
  224. ENGINE->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. if(hoverable && !isBlocked())
  262. {
  263. if(on)
  264. setState(EButtonState::HIGHLIGHTED);
  265. else
  266. setState(EButtonState::NORMAL);
  267. }
  268. /*if(pressedL && on) // WTF is this? When this is used?
  269. setState(PRESSED);*/
  270. std::string name = hoverTexts[vstd::to_underlying(getState())].empty()
  271. ? hoverTexts[0]
  272. : hoverTexts[vstd::to_underlying(getState())];
  273. if(!name.empty() && !isBlocked()) //if there is no name, there is nothing to display also
  274. {
  275. if (on)
  276. ENGINE->statusbar()->write(name);
  277. else
  278. ENGINE->statusbar()->clearIfMatching(name);
  279. }
  280. }
  281. ButtonBase::ButtonBase(Point position, const AnimationPath & defName, EShortcut key, bool playerColoredButton)
  282. : CKeyShortcut(key)
  283. , stateToIndex({0, 1, 2, 3})
  284. , state(EButtonState::NORMAL)
  285. {
  286. pos.x += position.x;
  287. pos.y += position.y;
  288. JsonPath jsonConfig = defName.toType<EResType::JSON>().addPrefix("CONFIG/WIDGETS/BUTTONS/");
  289. if (CResourceHandler::get()->existsResource(jsonConfig))
  290. {
  291. setConfigurable(jsonConfig, playerColoredButton);
  292. return;
  293. }
  294. else
  295. {
  296. setImage(defName, playerColoredButton);
  297. return;
  298. }
  299. }
  300. ButtonBase::~ButtonBase() = default;
  301. CButton::CButton(Point position, const AnimationPath &defName, const std::pair<std::string, std::string> &help, CFunctionList<void()> Callback, EShortcut key, bool playerColoredButton):
  302. ButtonBase(position, defName, key, playerColoredButton),
  303. callback(Callback),
  304. helpBox(help.second),
  305. actOnDown(false),
  306. hoverable(false),
  307. soundDisabled(false)
  308. {
  309. addUsedEvents(LCLICK | SHOW_POPUP | HOVER | KEYBOARD);
  310. hoverTexts[0] = help.first;
  311. }
  312. void ButtonBase::setPlayerColor(PlayerColor player)
  313. {
  314. if (image && image->isPlayerColored())
  315. image->setPlayerColor(player);
  316. }
  317. void CButton::showAll(Canvas & to)
  318. {
  319. CIntObject::showAll(to);
  320. if (borderColor)
  321. to.drawBorder(Rect::createAround(pos, 1), *borderColor);
  322. if (highlightedBorderColor && isHighlighted())
  323. {
  324. to.drawBorder(pos, *highlightedBorderColor);
  325. to.drawBorder(Rect(pos.topLeft() + Point(1,1), pos.dimensions() - Point(1,1)), *highlightedBorderColor);
  326. }
  327. }
  328. std::pair<std::string, std::string> CButton::tooltip()
  329. {
  330. return std::pair<std::string, std::string>();
  331. }
  332. std::pair<std::string, std::string> CButton::tooltipLocalized(const std::string & key)
  333. {
  334. return std::make_pair(
  335. LIBRARY->generaltexth->translate(key, "hover"),
  336. LIBRARY->generaltexth->translate(key, "help")
  337. );
  338. }
  339. std::pair<std::string, std::string> CButton::tooltip(const std::string & hover, const std::string & help)
  340. {
  341. return std::make_pair(hover, help);
  342. }
  343. CToggleBase::CToggleBase(CFunctionList<void (bool)> callback):
  344. callback(callback),
  345. selected(false),
  346. allowDeselection(true)
  347. {
  348. }
  349. CToggleBase::~CToggleBase() = default;
  350. void CToggleBase::doSelect(bool on)
  351. {
  352. // for overrides
  353. }
  354. void CToggleBase::setEnabled(bool enabled)
  355. {
  356. // for overrides
  357. }
  358. void CToggleBase::setSelectedSilent(bool on)
  359. {
  360. selected = on;
  361. doSelect(on);
  362. }
  363. void CToggleBase::setSelected(bool on)
  364. {
  365. bool changed = (on != selected);
  366. setSelectedSilent(on);
  367. if (changed)
  368. callback(on);
  369. }
  370. bool CToggleBase::isSelected() const
  371. {
  372. return selected;
  373. }
  374. bool CToggleBase::canActivate() const
  375. {
  376. return !selected || allowDeselection;
  377. }
  378. void CToggleBase::addCallback(const std::function<void(bool)> & function)
  379. {
  380. callback += function;
  381. }
  382. void CToggleBase::setAllowDeselection(bool on)
  383. {
  384. allowDeselection = on;
  385. }
  386. CToggleButton::CToggleButton(Point position, const AnimationPath &defName, const std::pair<std::string, std::string> &help,
  387. CFunctionList<void(bool)> callback, EShortcut key, bool playerColoredButton,
  388. CFunctionList<void()> callbackSelected):
  389. CButton(position, defName, help, 0, key, playerColoredButton),
  390. CToggleBase(callback),
  391. callbackSelected(callbackSelected)
  392. {
  393. addUsedEvents(DOUBLECLICK);
  394. }
  395. void CToggleButton::doSelect(bool on)
  396. {
  397. if (on)
  398. {
  399. setState(EButtonState::HIGHLIGHTED);
  400. }
  401. else
  402. {
  403. setState(EButtonState::NORMAL);
  404. }
  405. }
  406. void CToggleButton::setEnabled(bool enabled)
  407. {
  408. setState(enabled ? EButtonState::NORMAL : EButtonState::BLOCKED);
  409. }
  410. void CToggleButton::clickPressed(const Point & cursorPosition)
  411. {
  412. // force refresh
  413. hover(false);
  414. hover(true);
  415. if(isBlocked())
  416. return;
  417. if (canActivate())
  418. {
  419. ENGINE->sound().playSound(soundBase::button);
  420. ENGINE->input().hapticFeedback();
  421. setState(EButtonState::PRESSED);
  422. }
  423. }
  424. void CToggleButton::clickReleased(const Point & cursorPosition)
  425. {
  426. // force refresh
  427. hover(false);
  428. hover(true);
  429. if(isBlocked())
  430. return;
  431. if (getState() == EButtonState::PRESSED && canActivate())
  432. {
  433. onButtonClicked();
  434. setSelected(!isSelected());
  435. }
  436. else
  437. doSelect(isSelected()); // restore
  438. }
  439. void CToggleButton::clickCancel(const Point & cursorPosition)
  440. {
  441. // force refresh
  442. hover(false);
  443. hover(true);
  444. if(isBlocked())
  445. return;
  446. doSelect(isSelected());
  447. }
  448. void CToggleButton::clickDouble(const Point & cursorPosition)
  449. {
  450. if(callbackSelected)
  451. callbackSelected();
  452. }
  453. void CToggleGroup::addCallback(const std::function<void(int)> & callback)
  454. {
  455. onChange += callback;
  456. }
  457. void CToggleGroup::resetCallback()
  458. {
  459. onChange.clear();
  460. }
  461. void CToggleGroup::addToggle(int identifier, const std::shared_ptr<CToggleBase> & button)
  462. {
  463. if(auto intObj = std::dynamic_pointer_cast<CIntObject>(button)) // hack-ish workagound to avoid diamond problem with inheritance
  464. {
  465. addChild(intObj.get());
  466. }
  467. button->addCallback([this, identifier] (bool on) { if (on) selectionChanged(identifier);});
  468. button->setAllowDeselection(false);
  469. if(buttons.count(identifier)>0)
  470. logAnim->error("Duplicated toggle button id %d", identifier);
  471. buttons[identifier] = button;
  472. }
  473. CToggleGroup::CToggleGroup(const CFunctionList<void(int)> &OnChange)
  474. : onChange(OnChange), selectedID(-2)
  475. {
  476. }
  477. void CToggleGroup::setSelected(int id)
  478. {
  479. selectionChanged(id);
  480. }
  481. void CToggleGroup::setSelectedOnly(int id)
  482. {
  483. for(const auto & button : buttons)
  484. button.second->setEnabled(button.first == id);
  485. selectionChanged(id);
  486. }
  487. void CToggleGroup::selectionChanged(int to)
  488. {
  489. if (to == selectedID)
  490. return;
  491. int oldSelection = selectedID;
  492. selectedID = to;
  493. if (buttons.count(oldSelection))
  494. buttons[oldSelection]->setSelected(false);
  495. if (buttons.count(to))
  496. buttons[to]->setSelected(true);
  497. onChange(to);
  498. redraw();
  499. }
  500. int CToggleGroup::getSelected() const
  501. {
  502. return selectedID;
  503. }