Buttons.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  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/VCMI_Lib.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. void CButton::setHoverable(bool on)
  173. {
  174. hoverable = on;
  175. }
  176. void CButton::setSoundDisabled(bool on)
  177. {
  178. soundDisabled = on;
  179. }
  180. void CButton::setActOnDown(bool on)
  181. {
  182. actOnDown = on;
  183. }
  184. void CButton::setHelp(const std::pair<std::string, std::string> & help)
  185. {
  186. hoverTexts[0] = help.first;
  187. helpBox = help.second;
  188. }
  189. void CButton::block(bool on)
  190. {
  191. if(on || getState() == EButtonState::BLOCKED) //dont change button state if unblock requested, but it's not blocked
  192. setState(on ? EButtonState::BLOCKED : EButtonState::NORMAL);
  193. }
  194. void CButton::onButtonClicked()
  195. {
  196. // debug logging to figure out pressed button (and as result - player actions) in case of crash
  197. logAnim->trace("Button clicked at %dx%d", pos.x, pos.y);
  198. CIntObject * parent = this->parent;
  199. std::string prefix = "Parent is";
  200. while (parent)
  201. {
  202. logAnim->trace("%s%s at %dx%d", prefix, typeid(*parent).name(), parent->pos.x, parent->pos.y);
  203. parent = parent->parent;
  204. prefix = '\t' + prefix;
  205. }
  206. callback();
  207. }
  208. void CButton::clickPressed(const Point & cursorPosition)
  209. {
  210. if(isBlocked())
  211. return;
  212. if (getState() != EButtonState::PRESSED)
  213. {
  214. if (!soundDisabled)
  215. {
  216. ENGINE->sound().playSound(soundBase::button);
  217. ENGINE->input().hapticFeedback();
  218. }
  219. setState(EButtonState::PRESSED);
  220. if (actOnDown)
  221. onButtonClicked();
  222. }
  223. }
  224. void CButton::clickReleased(const Point & cursorPosition)
  225. {
  226. if (getState() == EButtonState::PRESSED)
  227. {
  228. if(hoverable && isHovered())
  229. setState(EButtonState::HIGHLIGHTED);
  230. else
  231. setState(EButtonState::NORMAL);
  232. if (!actOnDown)
  233. onButtonClicked();
  234. }
  235. }
  236. void CButton::clickCancel(const Point & cursorPosition)
  237. {
  238. if (getState() == EButtonState::PRESSED)
  239. {
  240. if(hoverable && isHovered())
  241. setState(EButtonState::HIGHLIGHTED);
  242. else
  243. setState(EButtonState::NORMAL);
  244. }
  245. }
  246. void CButton::showPopupWindow(const Point & cursorPosition)
  247. {
  248. callbackPopup();
  249. if(!helpBox.empty()) //there is no point to show window with nothing inside...
  250. CRClickPopup::createAndPush(helpBox);
  251. }
  252. void CButton::hover (bool on)
  253. {
  254. if(hoverable && !isBlocked())
  255. {
  256. if(on)
  257. setState(EButtonState::HIGHLIGHTED);
  258. else
  259. setState(EButtonState::NORMAL);
  260. }
  261. /*if(pressedL && on) // WTF is this? When this is used?
  262. setState(PRESSED);*/
  263. std::string name = hoverTexts[vstd::to_underlying(getState())].empty()
  264. ? hoverTexts[0]
  265. : hoverTexts[vstd::to_underlying(getState())];
  266. if(!name.empty() && !isBlocked()) //if there is no name, there is nothing to display also
  267. {
  268. if (on)
  269. ENGINE->statusbar()->write(name);
  270. else
  271. ENGINE->statusbar()->clearIfMatching(name);
  272. }
  273. }
  274. ButtonBase::ButtonBase(Point position, const AnimationPath & defName, EShortcut key, bool playerColoredButton)
  275. : CKeyShortcut(key)
  276. , stateToIndex({0, 1, 2, 3})
  277. , state(EButtonState::NORMAL)
  278. {
  279. pos.x += position.x;
  280. pos.y += position.y;
  281. JsonPath jsonConfig = defName.toType<EResType::JSON>().addPrefix("CONFIG/WIDGETS/BUTTONS/");
  282. if (CResourceHandler::get()->existsResource(jsonConfig))
  283. {
  284. setConfigurable(jsonConfig, playerColoredButton);
  285. return;
  286. }
  287. else
  288. {
  289. setImage(defName, playerColoredButton);
  290. return;
  291. }
  292. }
  293. ButtonBase::~ButtonBase() = default;
  294. CButton::CButton(Point position, const AnimationPath &defName, const std::pair<std::string, std::string> &help, CFunctionList<void()> Callback, EShortcut key, bool playerColoredButton):
  295. ButtonBase(position, defName, key, playerColoredButton),
  296. callback(Callback),
  297. helpBox(help.second),
  298. actOnDown(false),
  299. hoverable(false),
  300. soundDisabled(false)
  301. {
  302. addUsedEvents(LCLICK | SHOW_POPUP | HOVER | KEYBOARD);
  303. hoverTexts[0] = help.first;
  304. }
  305. void ButtonBase::setPlayerColor(PlayerColor player)
  306. {
  307. if (image && image->isPlayerColored())
  308. image->setPlayerColor(player);
  309. }
  310. void CButton::showAll(Canvas & to)
  311. {
  312. CIntObject::showAll(to);
  313. if (borderColor)
  314. to.drawBorder(Rect::createAround(pos, 1), *borderColor);
  315. }
  316. std::pair<std::string, std::string> CButton::tooltip()
  317. {
  318. return std::pair<std::string, std::string>();
  319. }
  320. std::pair<std::string, std::string> CButton::tooltipLocalized(const std::string & key)
  321. {
  322. return std::make_pair(
  323. VLC->generaltexth->translate(key, "hover"),
  324. VLC->generaltexth->translate(key, "help")
  325. );
  326. }
  327. std::pair<std::string, std::string> CButton::tooltip(const std::string & hover, const std::string & help)
  328. {
  329. return std::make_pair(hover, help);
  330. }
  331. CToggleBase::CToggleBase(CFunctionList<void (bool)> callback):
  332. callback(callback),
  333. selected(false),
  334. allowDeselection(true)
  335. {
  336. }
  337. CToggleBase::~CToggleBase() = default;
  338. void CToggleBase::doSelect(bool on)
  339. {
  340. // for overrides
  341. }
  342. void CToggleBase::setEnabled(bool enabled)
  343. {
  344. // for overrides
  345. }
  346. void CToggleBase::setSelectedSilent(bool on)
  347. {
  348. selected = on;
  349. doSelect(on);
  350. }
  351. void CToggleBase::setSelected(bool on)
  352. {
  353. bool changed = (on != selected);
  354. setSelectedSilent(on);
  355. if (changed)
  356. callback(on);
  357. }
  358. bool CToggleBase::isSelected() const
  359. {
  360. return selected;
  361. }
  362. bool CToggleBase::canActivate() const
  363. {
  364. return !selected || allowDeselection;
  365. }
  366. void CToggleBase::addCallback(const std::function<void(bool)> & function)
  367. {
  368. callback += function;
  369. }
  370. void CToggleBase::setAllowDeselection(bool on)
  371. {
  372. allowDeselection = on;
  373. }
  374. CToggleButton::CToggleButton(Point position, const AnimationPath &defName, const std::pair<std::string, std::string> &help,
  375. CFunctionList<void(bool)> callback, EShortcut key, bool playerColoredButton,
  376. CFunctionList<void()> callbackSelected):
  377. CButton(position, defName, help, 0, key, playerColoredButton),
  378. CToggleBase(callback),
  379. callbackSelected(callbackSelected)
  380. {
  381. addUsedEvents(DOUBLECLICK);
  382. }
  383. void CToggleButton::doSelect(bool on)
  384. {
  385. if (on)
  386. {
  387. setState(EButtonState::HIGHLIGHTED);
  388. }
  389. else
  390. {
  391. setState(EButtonState::NORMAL);
  392. }
  393. }
  394. void CToggleButton::setEnabled(bool enabled)
  395. {
  396. setState(enabled ? EButtonState::NORMAL : EButtonState::BLOCKED);
  397. }
  398. void CToggleButton::clickPressed(const Point & cursorPosition)
  399. {
  400. // force refresh
  401. hover(false);
  402. hover(true);
  403. if(isBlocked())
  404. return;
  405. if (canActivate())
  406. {
  407. ENGINE->sound().playSound(soundBase::button);
  408. ENGINE->input().hapticFeedback();
  409. setState(EButtonState::PRESSED);
  410. }
  411. }
  412. void CToggleButton::clickReleased(const Point & cursorPosition)
  413. {
  414. // force refresh
  415. hover(false);
  416. hover(true);
  417. if(isBlocked())
  418. return;
  419. if (getState() == EButtonState::PRESSED && canActivate())
  420. {
  421. onButtonClicked();
  422. setSelected(!isSelected());
  423. }
  424. else
  425. doSelect(isSelected()); // restore
  426. }
  427. void CToggleButton::clickCancel(const Point & cursorPosition)
  428. {
  429. // force refresh
  430. hover(false);
  431. hover(true);
  432. if(isBlocked())
  433. return;
  434. doSelect(isSelected());
  435. }
  436. void CToggleButton::clickDouble(const Point & cursorPosition)
  437. {
  438. if(callbackSelected)
  439. callbackSelected();
  440. }
  441. void CToggleGroup::addCallback(const std::function<void(int)> & callback)
  442. {
  443. onChange += callback;
  444. }
  445. void CToggleGroup::resetCallback()
  446. {
  447. onChange.clear();
  448. }
  449. void CToggleGroup::addToggle(int identifier, const std::shared_ptr<CToggleBase> & button)
  450. {
  451. if(auto intObj = std::dynamic_pointer_cast<CIntObject>(button)) // hack-ish workagound to avoid diamond problem with inheritance
  452. {
  453. addChild(intObj.get());
  454. }
  455. button->addCallback([=] (bool on) { if (on) selectionChanged(identifier);});
  456. button->setAllowDeselection(false);
  457. if(buttons.count(identifier)>0)
  458. logAnim->error("Duplicated toggle button id %d", identifier);
  459. buttons[identifier] = button;
  460. }
  461. CToggleGroup::CToggleGroup(const CFunctionList<void(int)> &OnChange)
  462. : onChange(OnChange), selectedID(-2)
  463. {
  464. }
  465. void CToggleGroup::setSelected(int id)
  466. {
  467. selectionChanged(id);
  468. }
  469. void CToggleGroup::setSelectedOnly(int id)
  470. {
  471. for(const auto & button : buttons)
  472. button.second->setEnabled(button.first == id);
  473. selectionChanged(id);
  474. }
  475. void CToggleGroup::selectionChanged(int to)
  476. {
  477. if (to == selectedID)
  478. return;
  479. int oldSelection = selectedID;
  480. selectedID = to;
  481. if (buttons.count(oldSelection))
  482. buttons[oldSelection]->setSelected(false);
  483. if (buttons.count(to))
  484. buttons[to]->setSelected(true);
  485. onChange(to);
  486. redraw();
  487. }
  488. int CToggleGroup::getSelected() const
  489. {
  490. return selectedID;
  491. }