Buttons.cpp 13 KB

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