VisualComponent.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. // zlib open source license
  2. //
  3. // Copyright (c) 2018 to 2019 David Forsgren Piuva
  4. //
  5. // This software is provided 'as-is', without any express or implied
  6. // warranty. In no event will the authors be held liable for any damages
  7. // arising from the use of this software.
  8. //
  9. // Permission is granted to anyone to use this software for any purpose,
  10. // including commercial applications, and to alter it and redistribute it
  11. // freely, subject to the following restrictions:
  12. //
  13. // 1. The origin of this software must not be misrepresented; you must not
  14. // claim that you wrote the original software. If you use this software
  15. // in a product, an acknowledgment in the product documentation would be
  16. // appreciated but is not required.
  17. //
  18. // 2. Altered source versions must be plainly marked as such, and must not be
  19. // misrepresented as being the original software.
  20. //
  21. // 3. This notice may not be removed or altered from any source
  22. // distribution.
  23. #include <stdint.h>
  24. #include "VisualComponent.h"
  25. #include "../image/internal/imageInternal.h"
  26. using namespace dsr;
  27. PERSISTENT_DEFINITION(VisualComponent)
  28. VisualComponent::VisualComponent() {}
  29. VisualComponent::~VisualComponent() {
  30. this->callback_destroyEvent();
  31. // Let the children know that the parent component no longer exists.
  32. for (int i = 0; i < this->getChildCount(); i++) {
  33. this->children[i]->parent = nullptr;
  34. }
  35. }
  36. IVector2D VisualComponent::getDesiredDimensions() {
  37. // Unless this virtual method is overridden, toolbars and such will try to give these dimensions to the component.
  38. return IVector2D(32, 32);
  39. }
  40. bool VisualComponent::isContainer() const {
  41. return true;
  42. }
  43. IRect VisualComponent::getLocation() {
  44. // If someone requested access to Left, Top, Right or Bottom, regionAccessed will be true
  45. if (this->regionAccessed) {
  46. // Now that a fixed location is requested, we need to recalculate the location from the flexible region based on parent dimensions
  47. this->updateLayout();
  48. this->regionAccessed = false;
  49. }
  50. return this->location;
  51. }
  52. void VisualComponent::setRegion(const FlexRegion &newRegion) {
  53. this->region = newRegion;
  54. }
  55. FlexRegion VisualComponent::getRegion() const {
  56. return this->region;
  57. }
  58. void VisualComponent::setVisible(bool visible) {
  59. this->visible.value = visible;
  60. }
  61. bool VisualComponent::getVisible() const {
  62. return this->visible.value;
  63. }
  64. void VisualComponent::setName(const String& newName) {
  65. this->name.value = newName;
  66. }
  67. String VisualComponent::getName() const {
  68. return this->name.value;
  69. }
  70. void VisualComponent::setIndex(int newIndex) {
  71. this->index.value = newIndex;
  72. }
  73. int VisualComponent::getIndex() const {
  74. return this->index.value;
  75. }
  76. void VisualComponent::setLocation(const IRect &newLocation) {
  77. IRect oldLocation = this->location;
  78. this->location = newLocation;
  79. if (oldLocation != newLocation) {
  80. this->updateLocationEvent(oldLocation, newLocation);
  81. }
  82. this->changedLocation(oldLocation, newLocation);
  83. }
  84. void VisualComponent::updateLayout() {
  85. this->setLocation(this->region.getNewLocation(this->givenSpace));
  86. }
  87. void VisualComponent::applyLayout(const IRect& givenSpace) {
  88. this->givenSpace = givenSpace;
  89. this->updateLayout();
  90. }
  91. void VisualComponent::updateLocationEvent(const IRect& oldLocation, const IRect& newLocation) {
  92. // Place each child component
  93. for (int i = 0; i < this->getChildCount(); i++) {
  94. this->children[i]->applyLayout(IRect(0, 0, newLocation.width(), newLocation.height()));
  95. }
  96. }
  97. // Check if any change requires the child layout to update.
  98. // Used to realign members of toolbars after a desired dimension changed.
  99. void VisualComponent::updateChildLocations() {
  100. if (this->childChanged) {
  101. this->updateLocationEvent(this->location, this->location);
  102. this->childChanged = false;
  103. }
  104. }
  105. // Offset may become non-zero when the origin is outside of targetImage from being clipped outside of the parent region
  106. void VisualComponent::draw(ImageRgbaU8& targetImage, const IVector2D& offset) {
  107. if (this->getVisible()) {
  108. this->updateChildLocations();
  109. IRect containerBound = this->getLocation() + offset;
  110. this->drawSelf(targetImage, containerBound);
  111. // Draw each child component
  112. for (int i = 0; i < this->getChildCount(); i++) {
  113. this->children[i]->drawClipped(targetImage, containerBound.upperLeft(), containerBound);
  114. }
  115. }
  116. }
  117. void VisualComponent::drawClipped(ImageRgbaU8 targetImage, const IVector2D& offset, const IRect& clipRegion) {
  118. IRect finalRegion = IRect::cut(clipRegion, IRect(0, 0, image_getWidth(targetImage), image_getHeight(targetImage)));
  119. if (finalRegion.hasArea()) {
  120. // TODO: Optimize allocation of sub-images
  121. ImageRgbaU8 target = image_getSubImage(targetImage, finalRegion);
  122. this->draw(target, offset - finalRegion.upperLeft());
  123. }
  124. }
  125. // A red rectangle is drawn as a placeholder if the class couldn't be found
  126. // TODO: Should the type name be remembered in the base class for serializing missing components?
  127. void VisualComponent::drawSelf(ImageRgbaU8& targetImage, const IRect &relativeLocation) {
  128. draw_rectangle(targetImage, relativeLocation, ColorRgbaI32(200, 50, 50, 255));
  129. }
  130. // Manual use with the correct type
  131. void VisualComponent::addChildComponent(std::shared_ptr<VisualComponent> child) {
  132. if (!this->isContainer()) {
  133. throwError(U"Cannot attach a child to a non-container parent component!\n");
  134. } else if (child.get() == this) {
  135. throwError(U"Cannot attach a component to itself!\n");
  136. } else if (child->hasChild(this)) {
  137. throwError(U"Cannot attach to its own parent as a child component!\n");
  138. } else {
  139. // Remove from any previous parent
  140. child->detachFromParent();
  141. // Update layout based on the new parent size
  142. child->applyLayout(IRect(0, 0, this->location.width(), this->location.height()));
  143. // Connect to the new parent
  144. this->children.push(child);
  145. this->childChanged = true;
  146. child->parent = this;
  147. }
  148. }
  149. // Automatic insertion from loading
  150. bool VisualComponent::addChild(std::shared_ptr<Persistent> child) {
  151. // Try to cast from base class Persistent to derived class VisualComponent
  152. std::shared_ptr<VisualComponent> visualComponent = std::dynamic_pointer_cast<VisualComponent>(child);
  153. if (visualComponent.get() == nullptr) {
  154. return false; // Wrong type!
  155. } else {
  156. this->addChildComponent(visualComponent);
  157. return true; // Success!
  158. }
  159. }
  160. int VisualComponent::getChildCount() const {
  161. return this->children.length();
  162. }
  163. std::shared_ptr<Persistent> VisualComponent::getChild(int index) const {
  164. if (index >= 0 && index < this->children.length()) {
  165. return this->children[index];
  166. } else {
  167. return std::shared_ptr<Persistent>(); // Null handle for out of bound.
  168. }
  169. }
  170. void VisualComponent::detachFromParent() {
  171. // Check if there's a parent component
  172. VisualComponent *parent = this->parent;
  173. if (parent != nullptr) {
  174. parent->childChanged = true;
  175. // If the removed component is focused from the parent, then remove focus so that the parent is focused instead.
  176. if (parent->focusComponent.get() == this) {
  177. parent->focusComponent = std::shared_ptr<VisualComponent>();
  178. }
  179. // Iterate over all children in the parent component
  180. for (int i = 0; i < parent->getChildCount(); i++) {
  181. std::shared_ptr<VisualComponent> current = parent->children[i];
  182. if (current.get() == this) {
  183. current->parent = nullptr; // Assign null
  184. parent->children.remove(i);
  185. return;
  186. }
  187. }
  188. }
  189. }
  190. bool VisualComponent::hasChild(VisualComponent *child) const {
  191. for (int i = 0; i < this->getChildCount(); i++) {
  192. std::shared_ptr<VisualComponent> current = this->children[i];
  193. if (current.get() == child) {
  194. return true; // Found the component
  195. } else {
  196. if (current->hasChild(child)) {
  197. return true; // Found the component recursively
  198. }
  199. }
  200. }
  201. return false; // Could not find the component
  202. }
  203. bool VisualComponent::hasChild(std::shared_ptr<VisualComponent> child) const {
  204. return this->hasChild(child.get());
  205. }
  206. std::shared_ptr<VisualComponent> VisualComponent::findChildByName(ReadableString name) const {
  207. for (int i = 0; i < this->getChildCount(); i++) {
  208. std::shared_ptr<VisualComponent> current = this->children[i];
  209. if (string_match(current->getName(), name)) {
  210. return current; // Found the component
  211. } else {
  212. std::shared_ptr<VisualComponent> searchResult = current->findChildByName(name);
  213. if (searchResult.get() != nullptr) {
  214. return searchResult; // Found the component recursively
  215. }
  216. }
  217. }
  218. return std::shared_ptr<VisualComponent>(); // Could not find the component
  219. }
  220. std::shared_ptr<VisualComponent> VisualComponent::findChildByNameAndIndex(ReadableString name, int index) const {
  221. for (int i = 0; i < this->getChildCount(); i++) {
  222. std::shared_ptr<VisualComponent> current = this->children[i];
  223. if (string_match(current->getName(), name) && current->getIndex() == index) {
  224. return current; // Found the component
  225. } else {
  226. std::shared_ptr<VisualComponent> searchResult = current->findChildByNameAndIndex(name, index);
  227. if (searchResult.get() != nullptr) {
  228. return searchResult; // Found the component recursively
  229. }
  230. }
  231. }
  232. return std::shared_ptr<VisualComponent>(); // Could not find the component
  233. }
  234. bool VisualComponent::pointIsInside(const IVector2D& pixelPosition) {
  235. return pixelPosition.x > this->location.left() && pixelPosition.x < this->location.right()
  236. && pixelPosition.y > this->location.top() && pixelPosition.y < this->location.bottom();
  237. }
  238. // Non-recursive top-down search
  239. std::shared_ptr<VisualComponent> VisualComponent::getDirectChild(const IVector2D& pixelPosition, bool includeInvisible) {
  240. // Iterate child components in reverse drawing order
  241. for (int i = this->getChildCount() - 1; i >= 0; i--) {
  242. std::shared_ptr<VisualComponent> currentChild = this->children[i];
  243. // Check if the point is inside the child component
  244. if ((currentChild->getVisible() || includeInvisible) && currentChild->pointIsInside(pixelPosition)) {
  245. return currentChild;
  246. }
  247. }
  248. // Return nothing if the point missed all child components
  249. return std::shared_ptr<VisualComponent>();
  250. }
  251. // Recursive top-down search
  252. std::shared_ptr<VisualComponent> VisualComponent::getTopChild(const IVector2D& pixelPosition, bool includeInvisible) {
  253. // Iterate child components in reverse drawing order
  254. for (int i = this->getChildCount() - 1; i >= 0; i--) {
  255. std::shared_ptr<VisualComponent> currentChild = this->children[i];
  256. // Check if the point is inside the child component
  257. if ((currentChild->getVisible() || includeInvisible) && currentChild->pointIsInside(pixelPosition)) {
  258. // Check if a component inside the child component is even higher up
  259. std::shared_ptr<VisualComponent> subChild = currentChild->getTopChild(pixelPosition - this->getLocation().upperLeft(), includeInvisible);
  260. if (subChild.get() != nullptr) {
  261. return subChild;
  262. } else {
  263. return currentChild;
  264. }
  265. }
  266. }
  267. // Return nothing if the point missed all child components
  268. return std::shared_ptr<VisualComponent>();
  269. }
  270. void VisualComponent::sendMouseEvent(const MouseEvent& event) {
  271. // Update the layout if needed
  272. this->updateChildLocations();
  273. // Convert to local coordinates recursively
  274. MouseEvent localEvent = event - this->getLocation().upperLeft();
  275. std::shared_ptr<VisualComponent> childComponent;
  276. // Grab a component on mouse down
  277. if (event.mouseEventType == MouseEventType::MouseDown) {
  278. childComponent = this->dragComponent = this->focusComponent = this->getDirectChild(localEvent.position, false);
  279. this->holdCount++;
  280. }
  281. if (this->holdCount > 0) {
  282. // If we're grabbing a component, keep sending events to it
  283. childComponent = this->dragComponent;
  284. } else if (this->getVisible() && this->pointIsInside(event.position)) {
  285. // If we're not grabbing a component, see if we can send the action to another component
  286. childComponent = this->getDirectChild(localEvent.position, false);
  287. }
  288. // Send the signal to a child component or itself
  289. if (childComponent.get() != nullptr) {
  290. childComponent->sendMouseEvent(localEvent);
  291. } else {
  292. this->receiveMouseEvent(event);
  293. }
  294. // Release a component on mouse up
  295. if (event.mouseEventType == MouseEventType::MouseUp) {
  296. this->holdCount--;
  297. if (this->holdCount <= 0) {
  298. this->dragComponent = std::shared_ptr<VisualComponent>(); // Abort drag
  299. this->holdCount = 0;
  300. }
  301. }
  302. }
  303. void VisualComponent::receiveMouseEvent(const MouseEvent& event) {
  304. if (event.mouseEventType == MouseEventType::MouseDown) {
  305. this->callback_mouseDownEvent(event);
  306. } else if (event.mouseEventType == MouseEventType::MouseUp) {
  307. this->callback_mouseUpEvent(event);
  308. } else if (event.mouseEventType == MouseEventType::MouseMove) {
  309. this->callback_mouseMoveEvent(event);
  310. } else if (event.mouseEventType == MouseEventType::Scroll) {
  311. this->callback_mouseScrollEvent(event);
  312. }
  313. }
  314. void VisualComponent::sendKeyboardEvent(const KeyboardEvent& event) {
  315. // Send the signal to a focused component or itself
  316. if (this->focusComponent.get() != nullptr) {
  317. this->focusComponent->sendKeyboardEvent(event);
  318. } else {
  319. this->receiveKeyboardEvent(event);
  320. }
  321. }
  322. void VisualComponent::receiveKeyboardEvent(const KeyboardEvent& event) {
  323. if (event.keyboardEventType == KeyboardEventType::KeyDown) {
  324. this->callback_keyDownEvent(event);
  325. } else if (event.keyboardEventType == KeyboardEventType::KeyUp) {
  326. this->callback_keyUpEvent(event);
  327. } else if (event.keyboardEventType == KeyboardEventType::KeyType) {
  328. this->callback_keyTypeEvent(event);
  329. }
  330. }
  331. void VisualComponent::applyTheme(VisualTheme theme) {
  332. this->theme = theme;
  333. this->changedTheme(theme);
  334. for (int i = 0; i < this->getChildCount(); i++) {
  335. this->children[i] -> applyTheme(theme);
  336. }
  337. }
  338. VisualTheme VisualComponent::getTheme() const {
  339. return this->theme;
  340. }
  341. void VisualComponent::changedTheme(VisualTheme newTheme) {}
  342. String VisualComponent::call(const ReadableString &methodName, const ReadableString &arguments) {
  343. throwError("Unimplemented custom call received");
  344. return U"";
  345. }
  346. bool VisualComponent::isFocused() {
  347. if (this->parent != nullptr) {
  348. // For child component, go back to the root and then follow the focus pointers to find out which component is focused within the whole tree.
  349. // One cannot just check if the parent points back directly, because old pointers may be left from a previous route.
  350. VisualComponent *root = this; while (root->parent != nullptr) { root = root->parent; }
  351. VisualComponent *leaf = root; while (leaf->focusComponent.get() != nullptr) { leaf = leaf->focusComponent.get(); }
  352. return leaf == this; // Focused if the root component points back to this component.
  353. } else {
  354. // Root component is focused if it does not redirect its focus to a child component.
  355. return this->focusComponent.get() == nullptr; // Focused if no child is focused.
  356. }
  357. }
  358. MediaResult dsr::component_generateImage(VisualTheme theme, MediaMethod &method, int width, int height, int red, int green, int blue, int pressed, int focused, int hover) {
  359. return method.callUsingKeywords([&theme, &method, width, height, red, green, blue, pressed, focused, hover](MediaMachine &machine, int methodIndex, int inputIndex, const ReadableString &argumentName){
  360. if (string_caseInsensitiveMatch(argumentName, U"width")) {
  361. machine_setInputByIndex(machine, methodIndex, inputIndex, width);
  362. } else if (string_caseInsensitiveMatch(argumentName, U"height")) {
  363. machine_setInputByIndex(machine, methodIndex, inputIndex, height);
  364. } else if (string_caseInsensitiveMatch(argumentName, U"pressed")) {
  365. machine_setInputByIndex(machine, methodIndex, inputIndex, pressed);
  366. } else if (string_caseInsensitiveMatch(argumentName, U"focused")) {
  367. machine_setInputByIndex(machine, methodIndex, inputIndex, focused);
  368. } else if (string_caseInsensitiveMatch(argumentName, U"hover")) {
  369. machine_setInputByIndex(machine, methodIndex, inputIndex, hover);
  370. } else if (string_caseInsensitiveMatch(argumentName, U"red")) {
  371. machine_setInputByIndex(machine, methodIndex, inputIndex, red);
  372. } else if (string_caseInsensitiveMatch(argumentName, U"green")) {
  373. machine_setInputByIndex(machine, methodIndex, inputIndex, green);
  374. } else if (string_caseInsensitiveMatch(argumentName, U"blue")) {
  375. machine_setInputByIndex(machine, methodIndex, inputIndex, blue);
  376. } else if (theme_assignMediaMachineArguments(theme, method.contextIndex, machine, methodIndex, inputIndex, argumentName)) {
  377. // Assigned by theme_assignMediaMachineArguments.
  378. } else {
  379. // TODO: Ask the theme for the argument using a specified style class for variations between different types of buttons, checkboxes, panels, et cetera.
  380. // Throw an exception if the theme did not provide an input argument to its own media function.
  381. throwError(U"Unhandled setting \"", argumentName, U"\" requested by the media method \"", machine_getMethodName(machine, methodIndex), U"\" in the visual theme!\n");
  382. }
  383. });
  384. }