Buttons.cpp 12 KB

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