VisualComponent.cpp 16 KB

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