Buttons.cpp 13 KB

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