Buttons.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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 "../gui/MouseButton.h"
  20. #include "../gui/Shortcut.h"
  21. #include "../gui/InterfaceObjectConfigurable.h"
  22. #include "../media/ISoundPlayer.h"
  23. #include "../windows/InfoWindows.h"
  24. #include "../render/Canvas.h"
  25. #include "../render/IRenderHandler.h"
  26. #include "../../lib/CConfigHandler.h"
  27. #include "../../lib/texts/CGeneralTextHandler.h"
  28. #include "../../lib/filesystem/Filesystem.h"
  29. #include "../../lib/VCMI_Lib.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. 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. ENGINE->sound().playSound(soundBase::button);
  216. ENGINE->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. ENGINE->statusbar()->write(name);
  269. else
  270. ENGINE->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. addUsedEvents(LCLICK | SHOW_POPUP | HOVER | KEYBOARD);
  302. hoverTexts[0] = help.first;
  303. }
  304. void ButtonBase::setPlayerColor(PlayerColor player)
  305. {
  306. if (image && image->isPlayerColored())
  307. image->setPlayerColor(player);
  308. }
  309. void CButton::showAll(Canvas & to)
  310. {
  311. CIntObject::showAll(to);
  312. if (borderColor)
  313. to.drawBorder(Rect::createAround(pos, 1), *borderColor);
  314. }
  315. std::pair<std::string, std::string> CButton::tooltip()
  316. {
  317. return std::pair<std::string, std::string>();
  318. }
  319. std::pair<std::string, std::string> CButton::tooltipLocalized(const std::string & key)
  320. {
  321. return std::make_pair(
  322. VLC->generaltexth->translate(key, "hover"),
  323. VLC->generaltexth->translate(key, "help")
  324. );
  325. }
  326. std::pair<std::string, std::string> CButton::tooltip(const std::string & hover, const std::string & help)
  327. {
  328. return std::make_pair(hover, help);
  329. }
  330. CToggleBase::CToggleBase(CFunctionList<void (bool)> callback):
  331. callback(callback),
  332. selected(false),
  333. allowDeselection(true)
  334. {
  335. }
  336. CToggleBase::~CToggleBase() = default;
  337. void CToggleBase::doSelect(bool on)
  338. {
  339. // for overrides
  340. }
  341. void CToggleBase::setEnabled(bool enabled)
  342. {
  343. // for overrides
  344. }
  345. void CToggleBase::setSelectedSilent(bool on)
  346. {
  347. selected = on;
  348. doSelect(on);
  349. }
  350. void CToggleBase::setSelected(bool on)
  351. {
  352. bool changed = (on != selected);
  353. setSelectedSilent(on);
  354. if (changed)
  355. callback(on);
  356. }
  357. bool CToggleBase::isSelected() const
  358. {
  359. return selected;
  360. }
  361. bool CToggleBase::canActivate() const
  362. {
  363. return !selected || allowDeselection;
  364. }
  365. void CToggleBase::addCallback(const std::function<void(bool)> & function)
  366. {
  367. callback += function;
  368. }
  369. void CToggleBase::setAllowDeselection(bool on)
  370. {
  371. allowDeselection = on;
  372. }
  373. CToggleButton::CToggleButton(Point position, const AnimationPath &defName, const std::pair<std::string, std::string> &help,
  374. CFunctionList<void(bool)> callback, EShortcut key, bool playerColoredButton,
  375. CFunctionList<void()> callbackSelected):
  376. CButton(position, defName, help, 0, key, playerColoredButton),
  377. CToggleBase(callback),
  378. callbackSelected(callbackSelected)
  379. {
  380. addUsedEvents(DOUBLECLICK);
  381. }
  382. void CToggleButton::doSelect(bool on)
  383. {
  384. if (on)
  385. {
  386. setState(EButtonState::HIGHLIGHTED);
  387. }
  388. else
  389. {
  390. setState(EButtonState::NORMAL);
  391. }
  392. }
  393. void CToggleButton::setEnabled(bool enabled)
  394. {
  395. setState(enabled ? EButtonState::NORMAL : EButtonState::BLOCKED);
  396. }
  397. void CToggleButton::clickPressed(const Point & cursorPosition)
  398. {
  399. // force refresh
  400. hover(false);
  401. hover(true);
  402. if(isBlocked())
  403. return;
  404. if (canActivate())
  405. {
  406. ENGINE->sound().playSound(soundBase::button);
  407. ENGINE->input().hapticFeedback();
  408. setState(EButtonState::PRESSED);
  409. }
  410. }
  411. void CToggleButton::clickReleased(const Point & cursorPosition)
  412. {
  413. // force refresh
  414. hover(false);
  415. hover(true);
  416. if(isBlocked())
  417. return;
  418. if (getState() == EButtonState::PRESSED && canActivate())
  419. {
  420. onButtonClicked();
  421. setSelected(!isSelected());
  422. }
  423. else
  424. doSelect(isSelected()); // restore
  425. }
  426. void CToggleButton::clickCancel(const Point & cursorPosition)
  427. {
  428. // force refresh
  429. hover(false);
  430. hover(true);
  431. if(isBlocked())
  432. return;
  433. doSelect(isSelected());
  434. }
  435. void CToggleButton::clickDouble(const Point & cursorPosition)
  436. {
  437. if(callbackSelected)
  438. callbackSelected();
  439. }
  440. void CToggleGroup::addCallback(const std::function<void(int)> & callback)
  441. {
  442. onChange += callback;
  443. }
  444. void CToggleGroup::resetCallback()
  445. {
  446. onChange.clear();
  447. }
  448. void CToggleGroup::addToggle(int identifier, const std::shared_ptr<CToggleBase> & button)
  449. {
  450. if(auto intObj = std::dynamic_pointer_cast<CIntObject>(button)) // hack-ish workagound to avoid diamond problem with inheritance
  451. {
  452. addChild(intObj.get());
  453. }
  454. button->addCallback([=] (bool on) { if (on) selectionChanged(identifier);});
  455. button->setAllowDeselection(false);
  456. if(buttons.count(identifier)>0)
  457. logAnim->error("Duplicated toggle button id %d", identifier);
  458. buttons[identifier] = button;
  459. }
  460. CToggleGroup::CToggleGroup(const CFunctionList<void(int)> &OnChange)
  461. : onChange(OnChange), selectedID(-2)
  462. {
  463. }
  464. void CToggleGroup::setSelected(int id)
  465. {
  466. selectionChanged(id);
  467. }
  468. void CToggleGroup::setSelectedOnly(int id)
  469. {
  470. for(const auto & button : buttons)
  471. button.second->setEnabled(button.first == id);
  472. selectionChanged(id);
  473. }
  474. void CToggleGroup::selectionChanged(int to)
  475. {
  476. if (to == selectedID)
  477. return;
  478. int oldSelection = selectedID;
  479. selectedID = to;
  480. if (buttons.count(oldSelection))
  481. buttons[oldSelection]->setSelected(false);
  482. if (buttons.count(to))
  483. buttons[to]->setSelected(true);
  484. onChange(to);
  485. redraw();
  486. }
  487. int CToggleGroup::getSelected() const
  488. {
  489. return selectedID;
  490. }