Buttons.cpp 12 KB

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