Buttons.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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 "../CMusicHandler.h"
  15. #include "../CGameInfo.h"
  16. #include "../CPlayerInterface.h"
  17. #include "../battle/BattleInterface.h"
  18. #include "../battle/BattleInterfaceClasses.h"
  19. #include "../eventsSDL/InputHandler.h"
  20. #include "../gui/CGuiHandler.h"
  21. #include "../gui/MouseButton.h"
  22. #include "../gui/Shortcut.h"
  23. #include "../gui/InterfaceObjectConfigurable.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::block(bool on)
  180. {
  181. if(on || getState() == EButtonState::BLOCKED) //dont change button state if unblock requested, but it's not blocked
  182. setState(on ? EButtonState::BLOCKED : EButtonState::NORMAL);
  183. }
  184. void CButton::onButtonClicked()
  185. {
  186. // debug logging to figure out pressed button (and as result - player actions) in case of crash
  187. logAnim->trace("Button clicked at %dx%d", pos.x, pos.y);
  188. CIntObject * parent = this->parent;
  189. std::string prefix = "Parent is";
  190. while (parent)
  191. {
  192. logAnim->trace("%s%s at %dx%d", prefix, typeid(*parent).name(), parent->pos.x, parent->pos.y);
  193. parent = parent->parent;
  194. prefix = '\t' + prefix;
  195. }
  196. callback();
  197. }
  198. void CButton::clickPressed(const Point & cursorPosition)
  199. {
  200. if(isBlocked())
  201. return;
  202. if (getState() != EButtonState::PRESSED)
  203. {
  204. if (!soundDisabled)
  205. {
  206. CCS->soundh->playSound(soundBase::button);
  207. GH.input().hapticFeedback();
  208. }
  209. setState(EButtonState::PRESSED);
  210. if (actOnDown)
  211. onButtonClicked();
  212. }
  213. }
  214. void CButton::clickReleased(const Point & cursorPosition)
  215. {
  216. if (getState() == EButtonState::PRESSED)
  217. {
  218. if(hoverable && isHovered())
  219. setState(EButtonState::HIGHLIGHTED);
  220. else
  221. setState(EButtonState::NORMAL);
  222. if (!actOnDown)
  223. onButtonClicked();
  224. }
  225. }
  226. void CButton::clickCancel(const Point & cursorPosition)
  227. {
  228. if (getState() == EButtonState::PRESSED)
  229. {
  230. if(hoverable && isHovered())
  231. setState(EButtonState::HIGHLIGHTED);
  232. else
  233. setState(EButtonState::NORMAL);
  234. }
  235. }
  236. void CButton::showPopupWindow(const Point & cursorPosition)
  237. {
  238. if(!helpBox.empty()) //there is no point to show window with nothing inside...
  239. CRClickPopup::createAndPush(helpBox);
  240. }
  241. void CButton::hover (bool on)
  242. {
  243. if(hoverable && !isBlocked())
  244. {
  245. if(on)
  246. setState(EButtonState::HIGHLIGHTED);
  247. else
  248. setState(EButtonState::NORMAL);
  249. }
  250. /*if(pressedL && on) // WTF is this? When this is used?
  251. setState(PRESSED);*/
  252. std::string name = hoverTexts[vstd::to_underlying(getState())].empty()
  253. ? hoverTexts[0]
  254. : hoverTexts[vstd::to_underlying(getState())];
  255. if(!name.empty() && !isBlocked()) //if there is no name, there is nothing to display also
  256. {
  257. if (on)
  258. GH.statusbar()->write(name);
  259. else
  260. GH.statusbar()->clearIfMatching(name);
  261. }
  262. }
  263. ButtonBase::ButtonBase(Point position, const AnimationPath & defName, EShortcut key, bool playerColoredButton)
  264. : CKeyShortcut(key)
  265. , stateToIndex({0, 1, 2, 3})
  266. , state(EButtonState::NORMAL)
  267. {
  268. pos.x += position.x;
  269. pos.y += position.y;
  270. JsonPath jsonConfig = defName.toType<EResType::JSON>().addPrefix("CONFIG/WIDGETS/BUTTONS/");
  271. if (CResourceHandler::get()->existsResource(jsonConfig))
  272. {
  273. setConfigurable(jsonConfig, playerColoredButton);
  274. return;
  275. }
  276. else
  277. {
  278. setImage(defName, playerColoredButton);
  279. return;
  280. }
  281. }
  282. ButtonBase::~ButtonBase() = default;
  283. CButton::CButton(Point position, const AnimationPath &defName, const std::pair<std::string, std::string> &help, CFunctionList<void()> Callback, EShortcut key, bool playerColoredButton):
  284. ButtonBase(position, defName, key, playerColoredButton),
  285. callback(Callback),
  286. helpBox(help.second),
  287. actOnDown(false),
  288. hoverable(false),
  289. soundDisabled(false)
  290. {
  291. defActions = 255-DISPOSE;
  292. addUsedEvents(LCLICK | SHOW_POPUP | HOVER | KEYBOARD);
  293. hoverTexts[0] = help.first;
  294. }
  295. void ButtonBase::setPlayerColor(PlayerColor player)
  296. {
  297. if (image && image->isPlayerColored())
  298. image->playerColored(player);
  299. }
  300. void CButton::showAll(Canvas & to)
  301. {
  302. CIntObject::showAll(to);
  303. if (borderColor)
  304. to.drawBorder(Rect::createAround(pos, 1), *borderColor);
  305. }
  306. std::pair<std::string, std::string> CButton::tooltip()
  307. {
  308. return std::pair<std::string, std::string>();
  309. }
  310. std::pair<std::string, std::string> CButton::tooltipLocalized(const std::string & key)
  311. {
  312. return std::make_pair(
  313. CGI->generaltexth->translate(key, "hover"),
  314. CGI->generaltexth->translate(key, "help")
  315. );
  316. }
  317. std::pair<std::string, std::string> CButton::tooltip(const std::string & hover, const std::string & help)
  318. {
  319. return std::make_pair(hover, help);
  320. }
  321. CToggleBase::CToggleBase(CFunctionList<void (bool)> callback):
  322. callback(callback),
  323. selected(false),
  324. allowDeselection(true)
  325. {
  326. }
  327. CToggleBase::~CToggleBase() = default;
  328. void CToggleBase::doSelect(bool on)
  329. {
  330. // for overrides
  331. }
  332. void CToggleBase::setEnabled(bool enabled)
  333. {
  334. // for overrides
  335. }
  336. void CToggleBase::setSelectedSilent(bool on)
  337. {
  338. selected = on;
  339. doSelect(on);
  340. }
  341. void CToggleBase::setSelected(bool on)
  342. {
  343. bool changed = (on != selected);
  344. setSelectedSilent(on);
  345. if (changed)
  346. callback(on);
  347. }
  348. bool CToggleBase::isSelected() const
  349. {
  350. return selected;
  351. }
  352. bool CToggleBase::canActivate() const
  353. {
  354. return !selected || allowDeselection;
  355. }
  356. void CToggleBase::addCallback(const std::function<void(bool)> & function)
  357. {
  358. callback += function;
  359. }
  360. void CToggleBase::setAllowDeselection(bool on)
  361. {
  362. allowDeselection = on;
  363. }
  364. CToggleButton::CToggleButton(Point position, const AnimationPath &defName, const std::pair<std::string, std::string> &help,
  365. CFunctionList<void(bool)> callback, EShortcut key, bool playerColoredButton):
  366. CButton(position, defName, help, 0, key, playerColoredButton),
  367. CToggleBase(callback)
  368. {
  369. }
  370. void CToggleButton::doSelect(bool on)
  371. {
  372. if (on)
  373. {
  374. setState(EButtonState::HIGHLIGHTED);
  375. }
  376. else
  377. {
  378. setState(EButtonState::NORMAL);
  379. }
  380. }
  381. void CToggleButton::setEnabled(bool enabled)
  382. {
  383. setState(enabled ? EButtonState::NORMAL : EButtonState::BLOCKED);
  384. }
  385. void CToggleButton::clickPressed(const Point & cursorPosition)
  386. {
  387. // force refresh
  388. hover(false);
  389. hover(true);
  390. if(isBlocked())
  391. return;
  392. if (canActivate())
  393. {
  394. CCS->soundh->playSound(soundBase::button);
  395. GH.input().hapticFeedback();
  396. setState(EButtonState::PRESSED);
  397. }
  398. }
  399. void CToggleButton::clickReleased(const Point & cursorPosition)
  400. {
  401. // force refresh
  402. hover(false);
  403. hover(true);
  404. if(isBlocked())
  405. return;
  406. if (getState() == EButtonState::PRESSED && canActivate())
  407. {
  408. onButtonClicked();
  409. setSelected(!isSelected());
  410. }
  411. else
  412. doSelect(isSelected()); // restore
  413. }
  414. void CToggleButton::clickCancel(const Point & cursorPosition)
  415. {
  416. // force refresh
  417. hover(false);
  418. hover(true);
  419. if(isBlocked())
  420. return;
  421. doSelect(isSelected());
  422. }
  423. void CToggleGroup::addCallback(const std::function<void(int)> & callback)
  424. {
  425. onChange += callback;
  426. }
  427. void CToggleGroup::resetCallback()
  428. {
  429. onChange.clear();
  430. }
  431. void CToggleGroup::addToggle(int identifier, const std::shared_ptr<CToggleBase> & button)
  432. {
  433. if(auto intObj = std::dynamic_pointer_cast<CIntObject>(button)) // hack-ish workagound to avoid diamond problem with inheritance
  434. {
  435. addChild(intObj.get());
  436. }
  437. button->addCallback([=] (bool on) { if (on) selectionChanged(identifier);});
  438. button->setAllowDeselection(false);
  439. if(buttons.count(identifier)>0)
  440. logAnim->error("Duplicated toggle button id %d", identifier);
  441. buttons[identifier] = button;
  442. }
  443. CToggleGroup::CToggleGroup(const CFunctionList<void(int)> &OnChange)
  444. : onChange(OnChange), selectedID(-2)
  445. {
  446. }
  447. void CToggleGroup::setSelected(int id)
  448. {
  449. selectionChanged(id);
  450. }
  451. void CToggleGroup::setSelectedOnly(int id)
  452. {
  453. for(const auto & button : buttons)
  454. button.second->setEnabled(button.first == id);
  455. selectionChanged(id);
  456. }
  457. void CToggleGroup::selectionChanged(int to)
  458. {
  459. if (to == selectedID)
  460. return;
  461. int oldSelection = selectedID;
  462. selectedID = to;
  463. if (buttons.count(oldSelection))
  464. buttons[oldSelection]->setSelected(false);
  465. if (buttons.count(to))
  466. buttons[to]->setSelected(true);
  467. onChange(to);
  468. redraw();
  469. }
  470. int CToggleGroup::getSelected() const
  471. {
  472. return selectedID;
  473. }