Buttons.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  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::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_CUSTOM_CAPTURING(255-DISPOSE);
  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_CUSTOM_CAPTURING(255-DISPOSE);
  84. configurable.reset();
  85. image = std::make_shared<CAnimImage>(defName, vstd::to_underlying(getState()));
  86. pos = image->pos;
  87. if (playerColoredButton)
  88. image->playerColored(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_CUSTOM_CAPTURING(255-DISPOSE);
  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->playerColored(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_CUSTOM_CAPTURING(255-DISPOSE);
  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. void CButton::setHoverable(bool on)
  172. {
  173. hoverable = on;
  174. }
  175. void CButton::setSoundDisabled(bool on)
  176. {
  177. soundDisabled = on;
  178. }
  179. void CButton::setActOnDown(bool on)
  180. {
  181. actOnDown = on;
  182. }
  183. void CButton::setHelp(const std::pair<std::string, std::string> & help)
  184. {
  185. hoverTexts[0] = help.first;
  186. helpBox = help.second;
  187. }
  188. void CButton::block(bool on)
  189. {
  190. if(on || getState() == EButtonState::BLOCKED) //dont change button state if unblock requested, but it's not blocked
  191. setState(on ? EButtonState::BLOCKED : EButtonState::NORMAL);
  192. }
  193. void CButton::onButtonClicked()
  194. {
  195. // debug logging to figure out pressed button (and as result - player actions) in case of crash
  196. logAnim->trace("Button clicked at %dx%d", pos.x, pos.y);
  197. CIntObject * parent = this->parent;
  198. std::string prefix = "Parent is";
  199. while (parent)
  200. {
  201. logAnim->trace("%s%s at %dx%d", prefix, typeid(*parent).name(), parent->pos.x, parent->pos.y);
  202. parent = parent->parent;
  203. prefix = '\t' + prefix;
  204. }
  205. callback();
  206. }
  207. void CButton::clickPressed(const Point & cursorPosition)
  208. {
  209. if(isBlocked())
  210. return;
  211. if (getState() != EButtonState::PRESSED)
  212. {
  213. if (!soundDisabled)
  214. {
  215. CCS->soundh->playSound(soundBase::button);
  216. GH.input().hapticFeedback();
  217. }
  218. setState(EButtonState::PRESSED);
  219. if (actOnDown)
  220. onButtonClicked();
  221. }
  222. }
  223. void CButton::clickReleased(const Point & cursorPosition)
  224. {
  225. if (getState() == EButtonState::PRESSED)
  226. {
  227. if(hoverable && isHovered())
  228. setState(EButtonState::HIGHLIGHTED);
  229. else
  230. setState(EButtonState::NORMAL);
  231. if (!actOnDown)
  232. onButtonClicked();
  233. }
  234. }
  235. void CButton::clickCancel(const Point & cursorPosition)
  236. {
  237. if (getState() == EButtonState::PRESSED)
  238. {
  239. if(hoverable && isHovered())
  240. setState(EButtonState::HIGHLIGHTED);
  241. else
  242. setState(EButtonState::NORMAL);
  243. }
  244. }
  245. void CButton::showPopupWindow(const Point & cursorPosition)
  246. {
  247. callbackPopup();
  248. if(!helpBox.empty()) //there is no point to show window with nothing inside...
  249. CRClickPopup::createAndPush(helpBox);
  250. }
  251. void CButton::hover (bool on)
  252. {
  253. if(hoverable && !isBlocked())
  254. {
  255. if(on)
  256. setState(EButtonState::HIGHLIGHTED);
  257. else
  258. setState(EButtonState::NORMAL);
  259. }
  260. /*if(pressedL && on) // WTF is this? When this is used?
  261. setState(PRESSED);*/
  262. std::string name = hoverTexts[vstd::to_underlying(getState())].empty()
  263. ? hoverTexts[0]
  264. : hoverTexts[vstd::to_underlying(getState())];
  265. if(!name.empty() && !isBlocked()) //if there is no name, there is nothing to display also
  266. {
  267. if (on)
  268. GH.statusbar()->write(name);
  269. else
  270. GH.statusbar()->clearIfMatching(name);
  271. }
  272. }
  273. ButtonBase::ButtonBase(Point position, const AnimationPath & defName, EShortcut key, bool playerColoredButton)
  274. : CKeyShortcut(key)
  275. , stateToIndex({0, 1, 2, 3})
  276. , state(EButtonState::NORMAL)
  277. {
  278. pos.x += position.x;
  279. pos.y += position.y;
  280. JsonPath jsonConfig = defName.toType<EResType::JSON>().addPrefix("CONFIG/WIDGETS/BUTTONS/");
  281. if (CResourceHandler::get()->existsResource(jsonConfig))
  282. {
  283. setConfigurable(jsonConfig, playerColoredButton);
  284. return;
  285. }
  286. else
  287. {
  288. setImage(defName, playerColoredButton);
  289. return;
  290. }
  291. }
  292. ButtonBase::~ButtonBase() = default;
  293. CButton::CButton(Point position, const AnimationPath &defName, const std::pair<std::string, std::string> &help, CFunctionList<void()> Callback, EShortcut key, bool playerColoredButton):
  294. ButtonBase(position, defName, key, playerColoredButton),
  295. callback(Callback),
  296. helpBox(help.second),
  297. actOnDown(false),
  298. hoverable(false),
  299. soundDisabled(false)
  300. {
  301. defActions = 255-DISPOSE;
  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->playerColored(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. CGI->generaltexth->translate(key, "hover"),
  324. CGI->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. CButton(position, defName, help, 0, key, playerColoredButton),
  377. CToggleBase(callback)
  378. {
  379. }
  380. void CToggleButton::doSelect(bool on)
  381. {
  382. if (on)
  383. {
  384. setState(EButtonState::HIGHLIGHTED);
  385. }
  386. else
  387. {
  388. setState(EButtonState::NORMAL);
  389. }
  390. }
  391. void CToggleButton::setEnabled(bool enabled)
  392. {
  393. setState(enabled ? EButtonState::NORMAL : EButtonState::BLOCKED);
  394. }
  395. void CToggleButton::clickPressed(const Point & cursorPosition)
  396. {
  397. // force refresh
  398. hover(false);
  399. hover(true);
  400. if(isBlocked())
  401. return;
  402. if (canActivate())
  403. {
  404. CCS->soundh->playSound(soundBase::button);
  405. GH.input().hapticFeedback();
  406. setState(EButtonState::PRESSED);
  407. }
  408. }
  409. void CToggleButton::clickReleased(const Point & cursorPosition)
  410. {
  411. // force refresh
  412. hover(false);
  413. hover(true);
  414. if(isBlocked())
  415. return;
  416. if (getState() == EButtonState::PRESSED && canActivate())
  417. {
  418. onButtonClicked();
  419. setSelected(!isSelected());
  420. }
  421. else
  422. doSelect(isSelected()); // restore
  423. }
  424. void CToggleButton::clickCancel(const Point & cursorPosition)
  425. {
  426. // force refresh
  427. hover(false);
  428. hover(true);
  429. if(isBlocked())
  430. return;
  431. doSelect(isSelected());
  432. }
  433. void CToggleGroup::addCallback(const std::function<void(int)> & callback)
  434. {
  435. onChange += callback;
  436. }
  437. void CToggleGroup::resetCallback()
  438. {
  439. onChange.clear();
  440. }
  441. void CToggleGroup::addToggle(int identifier, const std::shared_ptr<CToggleBase> & button)
  442. {
  443. if(auto intObj = std::dynamic_pointer_cast<CIntObject>(button)) // hack-ish workagound to avoid diamond problem with inheritance
  444. {
  445. addChild(intObj.get());
  446. }
  447. button->addCallback([=] (bool on) { if (on) selectionChanged(identifier);});
  448. button->setAllowDeselection(false);
  449. if(buttons.count(identifier)>0)
  450. logAnim->error("Duplicated toggle button id %d", identifier);
  451. buttons[identifier] = button;
  452. }
  453. CToggleGroup::CToggleGroup(const CFunctionList<void(int)> &OnChange)
  454. : onChange(OnChange), selectedID(-2)
  455. {
  456. }
  457. void CToggleGroup::setSelected(int id)
  458. {
  459. selectionChanged(id);
  460. }
  461. void CToggleGroup::setSelectedOnly(int id)
  462. {
  463. for(const auto & button : buttons)
  464. button.second->setEnabled(button.first == id);
  465. selectionChanged(id);
  466. }
  467. void CToggleGroup::selectionChanged(int to)
  468. {
  469. if (to == selectedID)
  470. return;
  471. int oldSelection = selectedID;
  472. selectedID = to;
  473. if (buttons.count(oldSelection))
  474. buttons[oldSelection]->setSelected(false);
  475. if (buttons.count(to))
  476. buttons[to]->setSelected(true);
  477. onChange(to);
  478. redraw();
  479. }
  480. int CToggleGroup::getSelected() const
  481. {
  482. return selectedID;
  483. }