Buttons.cpp 12 KB

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