Buttons.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  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::addHoverCallback(const std::function<void(bool)> & callback)
  61. {
  62. this->hoverCallback += callback;
  63. }
  64. void CButton::addPanningCallback(const std::function<void(const Point &, const Point &, const Point &)> & callback)
  65. {
  66. this->panningCallback += callback;
  67. }
  68. void ButtonBase::setTextOverlay(const std::string & Text, EFonts font, ColorRGBA color)
  69. {
  70. OBJECT_CONSTRUCTION_CUSTOM_CAPTURING(255-DISPOSE);
  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_CUSTOM_CAPTURING(255-DISPOSE);
  88. configurable.reset();
  89. image = std::make_shared<CAnimImage>(defName, vstd::to_underlying(getState()));
  90. pos = image->pos;
  91. if (playerColoredButton)
  92. image->playerColored(LOCPLINT->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_CUSTOM_CAPTURING(255-DISPOSE);
  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->playerColored(LOCPLINT->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_CUSTOM_CAPTURING(255-DISPOSE);
  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. 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. if(!helpBox.empty()) //there is no point to show window with nothing inside...
  252. CRClickPopup::createAndPush(helpBox);
  253. }
  254. void CButton::hover (bool on)
  255. {
  256. hoverCallback(on);
  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. void CButton::gesturePanning(const Point & initialPosition, const Point & currentPosition, const Point & lastUpdateDistance)
  278. {
  279. panningCallback(initialPosition, currentPosition, lastUpdateDistance);
  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. defActions = 255-DISPOSE;
  310. addUsedEvents(LCLICK | SHOW_POPUP | HOVER | KEYBOARD | GESTURE);
  311. hoverTexts[0] = help.first;
  312. }
  313. void ButtonBase::setPlayerColor(PlayerColor player)
  314. {
  315. if (image && image->isPlayerColored())
  316. image->playerColored(player);
  317. }
  318. void CButton::showAll(Canvas & to)
  319. {
  320. CIntObject::showAll(to);
  321. if (borderColor)
  322. to.drawBorder(Rect::createAround(pos, 1), *borderColor);
  323. }
  324. std::pair<std::string, std::string> CButton::tooltip()
  325. {
  326. return std::pair<std::string, std::string>();
  327. }
  328. std::pair<std::string, std::string> CButton::tooltipLocalized(const std::string & key)
  329. {
  330. return std::make_pair(
  331. CGI->generaltexth->translate(key, "hover"),
  332. CGI->generaltexth->translate(key, "help")
  333. );
  334. }
  335. std::pair<std::string, std::string> CButton::tooltip(const std::string & hover, const std::string & help)
  336. {
  337. return std::make_pair(hover, help);
  338. }
  339. CToggleBase::CToggleBase(CFunctionList<void (bool)> callback):
  340. callback(callback),
  341. selected(false),
  342. allowDeselection(true)
  343. {
  344. }
  345. CToggleBase::~CToggleBase() = default;
  346. void CToggleBase::doSelect(bool on)
  347. {
  348. // for overrides
  349. }
  350. void CToggleBase::setEnabled(bool enabled)
  351. {
  352. // for overrides
  353. }
  354. void CToggleBase::setSelectedSilent(bool on)
  355. {
  356. selected = on;
  357. doSelect(on);
  358. }
  359. void CToggleBase::setSelected(bool on)
  360. {
  361. bool changed = (on != selected);
  362. setSelectedSilent(on);
  363. if (changed)
  364. callback(on);
  365. }
  366. bool CToggleBase::isSelected() const
  367. {
  368. return selected;
  369. }
  370. bool CToggleBase::canActivate() const
  371. {
  372. return !selected || allowDeselection;
  373. }
  374. void CToggleBase::addCallback(const std::function<void(bool)> & function)
  375. {
  376. callback += function;
  377. }
  378. void CToggleBase::setAllowDeselection(bool on)
  379. {
  380. allowDeselection = on;
  381. }
  382. CToggleButton::CToggleButton(Point position, const AnimationPath &defName, const std::pair<std::string, std::string> &help,
  383. CFunctionList<void(bool)> callback, EShortcut key, bool playerColoredButton):
  384. CButton(position, defName, help, 0, key, playerColoredButton),
  385. CToggleBase(callback)
  386. {
  387. }
  388. void CToggleButton::doSelect(bool on)
  389. {
  390. if (on)
  391. {
  392. setState(EButtonState::HIGHLIGHTED);
  393. }
  394. else
  395. {
  396. setState(EButtonState::NORMAL);
  397. }
  398. }
  399. void CToggleButton::setEnabled(bool enabled)
  400. {
  401. setState(enabled ? EButtonState::NORMAL : EButtonState::BLOCKED);
  402. }
  403. void CToggleButton::clickPressed(const Point & cursorPosition)
  404. {
  405. // force refresh
  406. hover(false);
  407. hover(true);
  408. if(isBlocked())
  409. return;
  410. if (canActivate())
  411. {
  412. CCS->soundh->playSound(soundBase::button);
  413. GH.input().hapticFeedback();
  414. setState(EButtonState::PRESSED);
  415. }
  416. }
  417. void CToggleButton::clickReleased(const Point & cursorPosition)
  418. {
  419. // force refresh
  420. hover(false);
  421. hover(true);
  422. if(isBlocked())
  423. return;
  424. if (getState() == EButtonState::PRESSED && canActivate())
  425. {
  426. onButtonClicked();
  427. setSelected(!isSelected());
  428. }
  429. else
  430. doSelect(isSelected()); // restore
  431. }
  432. void CToggleButton::clickCancel(const Point & cursorPosition)
  433. {
  434. // force refresh
  435. hover(false);
  436. hover(true);
  437. if(isBlocked())
  438. return;
  439. doSelect(isSelected());
  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. }