VisualComponent.cpp 16 KB

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