You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

552 lines
19KB

  1. #pragma once
  2. #include <list>
  3. #include <common.hpp>
  4. #include <math.hpp>
  5. #include <window/Window.hpp>
  6. #include <color.hpp>
  7. #include <widget/event.hpp>
  8. #include <weakptr.hpp>
  9. namespace rack {
  10. /** Base UI widget types */
  11. namespace widget {
  12. /** A node in the 2D [scene graph](https://en.wikipedia.org/wiki/Scene_graph).
  13. The bounding box of a Widget is a rectangle specified by `box` relative to their parent.
  14. The appearance is defined by overriding `draw()`, and the behavior is defined by overriding `step()` and `on*()` event handlers.
  15. */
  16. struct Widget : WeakBase {
  17. /** Position relative to parent and size of widget. */
  18. math::Rect box = math::Rect(math::Vec(), math::Vec(INFINITY, INFINITY));
  19. /** Automatically set when Widget is added as a child to another Widget */
  20. Widget* parent = NULL;
  21. std::list<Widget*> children;
  22. /** Disables rendering but allow stepping.
  23. Use isVisible(), setVisible(), show(), or hide() instead of using this variable directly.
  24. */
  25. bool visible = true;
  26. /** If set to true, parent will delete Widget in the next step().
  27. Use requestDelete() instead of using this variable directly.
  28. */
  29. bool requestedDelete = false;
  30. virtual ~Widget();
  31. math::Rect getBox();
  32. void setBox(math::Rect box);
  33. math::Vec getPosition();
  34. void setPosition(math::Vec pos);
  35. math::Vec getSize();
  36. void setSize(math::Vec size);
  37. widget::Widget* getParent();
  38. bool isVisible();
  39. void setVisible(bool visible);
  40. void show() {
  41. setVisible(true);
  42. }
  43. void hide() {
  44. setVisible(false);
  45. }
  46. void requestDelete();
  47. /** Returns the smallest rectangle containing this widget's children (visible and invisible) in its local coordinates.
  48. Returns `Rect(Vec(inf, inf), Vec(-inf, -inf))` if there are no children.
  49. */
  50. virtual math::Rect getChildrenBoundingBox();
  51. virtual math::Rect getVisibleChildrenBoundingBox();
  52. /** Returns whether `ancestor` is a parent or distant parent of this widget.
  53. */
  54. bool isDescendantOf(Widget* ancestor);
  55. /** Returns `v` (given in local coordinates) transformed into the coordinate system of `ancestor`.
  56. */
  57. virtual math::Vec getRelativeOffset(math::Vec v, Widget* ancestor);
  58. /** Returns `v` transformed into world/root/global/absolute coordinates.
  59. */
  60. math::Vec getAbsoluteOffset(math::Vec v) {
  61. return getRelativeOffset(v, NULL);
  62. }
  63. /** Returns the zoom level in the coordinate system of `ancestor`.
  64. Only `ZoomWidget` should override this to return value other than 1.
  65. */
  66. virtual float getRelativeZoom(Widget* ancestor);
  67. float getAbsoluteZoom() {
  68. return getRelativeZoom(NULL);
  69. }
  70. /** Returns a subset of the given Rect bounded by the box of this widget and all ancestors.
  71. */
  72. virtual math::Rect getViewport(math::Rect r);
  73. template <class T>
  74. T* getAncestorOfType() {
  75. if (!parent)
  76. return NULL;
  77. T* p = dynamic_cast<T*>(parent);
  78. if (p)
  79. return p;
  80. return parent->getAncestorOfType<T>();
  81. }
  82. template <class T>
  83. T* getFirstDescendantOfType() {
  84. for (Widget* child : children) {
  85. T* c = dynamic_cast<T*>(child);
  86. if (c)
  87. return c;
  88. c = child->getFirstDescendantOfType<T>();
  89. if (c)
  90. return c;
  91. }
  92. return NULL;
  93. }
  94. /** Checks if the given widget is a child of `this` widget.
  95. */
  96. bool hasChild(Widget* child);
  97. /** Adds widget to the top of the children.
  98. Gives ownership of widget to this widget instance.
  99. */
  100. void addChild(Widget* child);
  101. /** Adds widget to the bottom of the children.
  102. */
  103. void addChildBottom(Widget* child);
  104. /** Adds widget directly below another widget.
  105. The sibling widget must already be a child of `this` widget.
  106. */
  107. void addChildBelow(Widget* child, Widget* sibling);
  108. void addChildAbove(Widget* child, Widget* sibling);
  109. /** Removes widget from list of children if it exists.
  110. Does not delete widget but transfers ownership to caller
  111. */
  112. void removeChild(Widget* child);
  113. /** Removes and deletes all children */
  114. void clearChildren();
  115. /** Advances the module by one frame */
  116. virtual void step();
  117. struct DrawArgs {
  118. NVGcontext* vg = NULL;
  119. /** Local box representing the visible viewport. */
  120. math::Rect clipBox;
  121. NVGLUframebuffer* fb = NULL;
  122. };
  123. /** Draws the widget to the NanoVG context.
  124. When overriding, call the superclass's `draw(args)` to recurse to children.
  125. */
  126. virtual void draw(const DrawArgs& args);
  127. /** Override draw(const DrawArgs &args) instead */
  128. DEPRECATED virtual void draw(NVGcontext* vg) {}
  129. /** Draw additional layers.
  130. Custom widgets may draw its children multiple times on different layers, passing an arbitrary layer number each time.
  131. Layer 0 calls children's draw().
  132. When overriding, always wrap draw commands in `if (layer == ...) {}` to avoid drawing on all layers.
  133. When overriding, call the superclass's `drawLayer(args, layer)` to recurse to children.
  134. */
  135. virtual void drawLayer(const DrawArgs& args, int layer);
  136. /** Draws a particular child. */
  137. void drawChild(Widget* child, const DrawArgs& args, int layer = 0);
  138. // Events
  139. /** Recurses an event to all visible Widgets */
  140. template <typename TMethod, class TEvent>
  141. void recurseEvent(TMethod f, const TEvent& e) {
  142. for (auto it = children.rbegin(); it != children.rend(); it++) {
  143. // Stop propagation if requested
  144. if (!e.isPropagating())
  145. break;
  146. Widget* child = *it;
  147. // Don't filter child by visibility. Typically only position events need to be filtered by visibility.
  148. // if (!child->visible)
  149. // continue;
  150. // Clone event for (currently) no reason
  151. TEvent e2 = e;
  152. // Call child event handler
  153. (child->*f)(e2);
  154. }
  155. }
  156. /** Recurses an event to all visible Widgets until it is consumed. */
  157. template <typename TMethod, class TEvent>
  158. void recursePositionEvent(TMethod f, const TEvent& e) {
  159. for (auto it = children.rbegin(); it != children.rend(); it++) {
  160. // Stop propagation if requested
  161. if (!e.isPropagating())
  162. break;
  163. Widget* child = *it;
  164. // Filter child by visibility and position
  165. if (!child->visible)
  166. continue;
  167. if (!child->box.contains(e.pos))
  168. continue;
  169. // Clone event and adjust its position
  170. TEvent e2 = e;
  171. e2.pos = e.pos.minus(child->box.pos);
  172. // Call child event handler
  173. (child->*f)(e2);
  174. }
  175. }
  176. using BaseEvent = widget::BaseEvent;
  177. /** An event prototype with a vector position. */
  178. struct PositionBaseEvent {
  179. /** The pixel coordinate where the event occurred, relative to the Widget it is called on. */
  180. math::Vec pos;
  181. };
  182. /** Occurs every frame when the mouse is hovering over a Widget.
  183. Recurses.
  184. Consume this event to allow Enter and Leave to occur.
  185. */
  186. struct HoverEvent : BaseEvent, PositionBaseEvent {
  187. /** Change in mouse position since the last frame. Can be zero. */
  188. math::Vec mouseDelta;
  189. };
  190. virtual void onHover(const HoverEvent& e) {
  191. recursePositionEvent(&Widget::onHover, e);
  192. }
  193. /** Occurs each mouse button press or release.
  194. Recurses.
  195. Consume this event to allow DoubleClick, Select, Deselect, SelectKey, SelectText, DragStart, DragEnd, DragMove, and DragDrop to occur.
  196. */
  197. struct ButtonEvent : BaseEvent, PositionBaseEvent {
  198. /** GLFW_MOUSE_BUTTON_LEFT, GLFW_MOUSE_BUTTON_RIGHT, GLFW_MOUSE_BUTTON_MIDDLE, etc. */
  199. int button;
  200. /** GLFW_PRESS or GLFW_RELEASE */
  201. int action;
  202. /** GLFW_MOD_* */
  203. int mods;
  204. };
  205. virtual void onButton(const ButtonEvent& e) {
  206. recursePositionEvent(&Widget::onButton, e);
  207. }
  208. /** Occurs when the left mouse button is pressed a second time on the same Widget within a time duration.
  209. Must consume the Button event (on left button press) to receive this event.
  210. */
  211. struct DoubleClickEvent : BaseEvent {};
  212. virtual void onDoubleClick(const DoubleClickEvent& e) {}
  213. /** An event prototype with a GLFW key. */
  214. struct KeyBaseEvent {
  215. /** The key corresponding to what it would be called in its position on a QWERTY US keyboard.
  216. For example, the WASD directional keys used for first-person shooters will always be reported as "WASD", regardless if they say "ZQSD" on an AZERTY keyboard.
  217. You should usually not use these for printable characters such as "Ctrl+V" key commands. Instead, use `keyName`.
  218. You *should* use these for non-printable keys, such as Escape, arrow keys, Home, F1-12, etc.
  219. You should also use this for Enter, Tab, and Space. Although they are printable keys, they do not appear in `keyName`.
  220. See GLFW_KEY_* for the list of possible values.
  221. */
  222. int key;
  223. /** Platform-dependent "software" key code.
  224. This variable is only included for completion. There should be no reason for you to use this.
  225. You should instead use `key` (for non-printable characters) or `keyName` (for printable characters).
  226. Values are platform independent and can change between different keyboards or keyboard layouts on the same OS.
  227. */
  228. int scancode;
  229. /** String containing the lowercase key name, if it produces a printable character.
  230. This is the only variable that correctly represents the label printed on any keyboard layout, whether it's QWERTY, AZERTY, QWERTZ, Dvorak, etc.
  231. For example, if the user presses the key labeled "q" regardless of the key position, `keyName` will be "q".
  232. For non-printable characters this is an empty string.
  233. Enter, Tab, and Space do not give a `keyName`. Use `key` instead.
  234. Shift has no effect on the key name. Shift+1 results in "1", Shift+q results in "q", etc.
  235. */
  236. std::string keyName;
  237. /** The type of event occurring with the key.
  238. Possible values are GLFW_RELEASE, GLFW_PRESS, GLFW_REPEAT, or RACK_HELD.
  239. RACK_HELD is sent every frame while the key is held.
  240. */
  241. int action;
  242. /** Bitwise OR of key modifiers, such as Ctrl or Shift.
  243. Use (mods & RACK_MOD_MASK) == RACK_MOD_CTRL to check for Ctrl on Linux and Windows but Cmd on Mac.
  244. See GLFW_MOD_* for the list of possible values.
  245. */
  246. int mods;
  247. };
  248. /** Occurs when a key is pressed, released, or repeated while the mouse is hovering a Widget.
  249. Recurses.
  250. */
  251. struct HoverKeyEvent : BaseEvent, PositionBaseEvent, KeyBaseEvent {};
  252. virtual void onHoverKey(const HoverKeyEvent& e) {
  253. recursePositionEvent(&Widget::onHoverKey, e);
  254. }
  255. /** An event prototype with a Unicode character. */
  256. struct TextBaseEvent {
  257. /** Unicode code point of the character */
  258. int codepoint;
  259. };
  260. /** Occurs when a character is typed while the mouse is hovering a Widget.
  261. Recurses.
  262. */
  263. struct HoverTextEvent : BaseEvent, PositionBaseEvent, TextBaseEvent {};
  264. virtual void onHoverText(const HoverTextEvent& e) {
  265. recursePositionEvent(&Widget::onHoverText, e);
  266. }
  267. /** Occurs when the mouse scroll wheel is moved while the mouse is hovering a Widget.
  268. Recurses.
  269. */
  270. struct HoverScrollEvent : BaseEvent, PositionBaseEvent {
  271. /** Change of scroll wheel position. */
  272. math::Vec scrollDelta;
  273. };
  274. virtual void onHoverScroll(const HoverScrollEvent& e) {
  275. recursePositionEvent(&Widget::onHoverScroll, e);
  276. }
  277. /** Occurs when a Widget begins consuming the Hover event.
  278. Must consume the Hover event to receive this event.
  279. The target sets `hoveredWidget`, which allows Leave to occur.
  280. */
  281. struct EnterEvent : BaseEvent {};
  282. virtual void onEnter(const EnterEvent& e) {}
  283. /** Occurs when a different Widget is entered.
  284. Must consume the Hover event (when a Widget is entered) to receive this event.
  285. */
  286. struct LeaveEvent : BaseEvent {};
  287. virtual void onLeave(const LeaveEvent& e) {}
  288. /** Occurs when a Widget begins consuming the Button press event for the left mouse button.
  289. Must consume the Button event (on left button press) to receive this event.
  290. The target sets `selectedWidget`, which allows SelectText and SelectKey to occur.
  291. */
  292. struct SelectEvent : BaseEvent {};
  293. virtual void onSelect(const SelectEvent& e) {}
  294. /** Occurs when a different Widget is selected.
  295. Must consume the Button event (on left button press, when the Widget is selected) to receive this event.
  296. */
  297. struct DeselectEvent : BaseEvent {};
  298. virtual void onDeselect(const DeselectEvent& e) {}
  299. /** Occurs when a key is pressed, released, or repeated while a Widget is selected.
  300. Must consume to prevent HoverKey from being triggered.
  301. */
  302. struct SelectKeyEvent : BaseEvent, KeyBaseEvent {};
  303. virtual void onSelectKey(const SelectKeyEvent& e) {}
  304. /** Occurs when text is typed while a Widget is selected.
  305. Must consume to prevent HoverKey from being triggered.
  306. */
  307. struct SelectTextEvent : BaseEvent, TextBaseEvent {};
  308. virtual void onSelectText(const SelectTextEvent& e) {}
  309. struct DragBaseEvent : BaseEvent {
  310. /** The mouse button held while dragging. */
  311. int button;
  312. };
  313. /** Occurs when a Widget begins being dragged.
  314. Must consume the Button event (on press) to receive this event.
  315. The target sets `draggedWidget`, which allows DragEnd, DragMove, DragHover, DragEnter, and DragDrop to occur.
  316. */
  317. struct DragStartEvent : DragBaseEvent {};
  318. virtual void onDragStart(const DragStartEvent& e) {}
  319. /** Occurs when a Widget stops being dragged by releasing the mouse button.
  320. Must consume the Button event (on press, when the Widget drag begins) to receive this event.
  321. */
  322. struct DragEndEvent : DragBaseEvent {};
  323. virtual void onDragEnd(const DragEndEvent& e) {}
  324. /** Occurs every frame on the dragged Widget.
  325. Must consume the Button event (on press, when the Widget drag begins) to receive this event.
  326. */
  327. struct DragMoveEvent : DragBaseEvent {
  328. /** Change in mouse position since the last frame. Can be zero. */
  329. math::Vec mouseDelta;
  330. };
  331. virtual void onDragMove(const DragMoveEvent& e) {}
  332. /** Occurs every frame when the mouse is hovering over a Widget while another Widget (possibly the same one) is being dragged.
  333. Recurses.
  334. Consume this event to allow DragEnter and DragLeave to occur.
  335. */
  336. struct DragHoverEvent : DragBaseEvent, PositionBaseEvent {
  337. /** The dragged widget */
  338. Widget* origin = NULL;
  339. /** Change in mouse position since the last frame. Can be zero. */
  340. math::Vec mouseDelta;
  341. };
  342. virtual void onDragHover(const DragHoverEvent& e) {
  343. recursePositionEvent(&Widget::onDragHover, e);
  344. }
  345. /** Occurs when the mouse enters a Widget while dragging.
  346. Must consume the DragHover event to receive this event.
  347. The target sets `draggedWidget`, which allows DragLeave to occur.
  348. */
  349. struct DragEnterEvent : DragBaseEvent {
  350. /** The dragged widget */
  351. Widget* origin = NULL;
  352. };
  353. virtual void onDragEnter(const DragEnterEvent& e) {}
  354. /** Occurs when the mouse leaves a Widget while dragging.
  355. Must consume the DragHover event (when the Widget is entered) to receive this event.
  356. */
  357. struct DragLeaveEvent : DragBaseEvent {
  358. /** The dragged widget */
  359. Widget* origin = NULL;
  360. };
  361. virtual void onDragLeave(const DragLeaveEvent& e) {}
  362. /** Occurs when the mouse button is released over a Widget while dragging.
  363. Must consume the Button event (on release) to receive this event.
  364. */
  365. struct DragDropEvent : DragBaseEvent {
  366. /** The dragged widget */
  367. Widget* origin = NULL;
  368. };
  369. virtual void onDragDrop(const DragDropEvent& e) {}
  370. /** Occurs when a selection of files from the operating system is dropped onto a Widget.
  371. Recurses.
  372. */
  373. struct PathDropEvent : BaseEvent, PositionBaseEvent {
  374. PathDropEvent(const std::vector<std::string>& paths) : paths(paths) {}
  375. /** List of file paths in the dropped selection */
  376. const std::vector<std::string>& paths;
  377. };
  378. virtual void onPathDrop(const PathDropEvent& e) {
  379. recursePositionEvent(&Widget::onPathDrop, e);
  380. }
  381. /** Occurs after a certain action is triggered on a Widget.
  382. The concept of an "action" is defined by the type of Widget.
  383. */
  384. struct ActionEvent : BaseEvent {};
  385. virtual void onAction(const ActionEvent& e) {}
  386. /** Occurs after the value of a Widget changes.
  387. The concept of a "value" is defined by the type of Widget.
  388. */
  389. struct ChangeEvent : BaseEvent {};
  390. virtual void onChange(const ChangeEvent& e) {}
  391. /** Occurs when the pixel buffer of this module must be refreshed.
  392. Recurses.
  393. */
  394. struct DirtyEvent : BaseEvent {};
  395. virtual void onDirty(const DirtyEvent& e) {
  396. recurseEvent(&Widget::onDirty, e);
  397. }
  398. /** Occurs after a Widget's position is set by Widget::setPosition().
  399. */
  400. struct RepositionEvent : BaseEvent {};
  401. virtual void onReposition(const RepositionEvent& e) {}
  402. /** Occurs after a Widget's size is set by Widget::setSize().
  403. */
  404. struct ResizeEvent : BaseEvent {};
  405. virtual void onResize(const ResizeEvent& e) {}
  406. /** Occurs after a Widget is added to a parent.
  407. */
  408. struct AddEvent : BaseEvent {};
  409. virtual void onAdd(const AddEvent& e) {}
  410. /** Occurs before a Widget is removed from its parent.
  411. */
  412. struct RemoveEvent : BaseEvent {};
  413. virtual void onRemove(const RemoveEvent& e) {}
  414. /** Occurs after a Widget is shown with Widget::show().
  415. Recurses.
  416. */
  417. struct ShowEvent : BaseEvent {};
  418. virtual void onShow(const ShowEvent& e) {
  419. recurseEvent(&Widget::onShow, e);
  420. }
  421. /** Occurs after a Widget is hidden with Widget::hide().
  422. Recurses.
  423. */
  424. struct HideEvent : BaseEvent {};
  425. virtual void onHide(const HideEvent& e) {
  426. recurseEvent(&Widget::onHide, e);
  427. }
  428. /** Occurs after the Window (including OpenGL and NanoVG contexts) are created.
  429. Recurses.
  430. */
  431. struct ContextCreateEvent : BaseEvent {
  432. NVGcontext* vg;
  433. };
  434. virtual void onContextCreate(const ContextCreateEvent& e) {
  435. recurseEvent(&Widget::onContextCreate, e);
  436. }
  437. /** Occurs before the Window (including OpenGL and NanoVG contexts) are destroyed.
  438. Recurses.
  439. */
  440. struct ContextDestroyEvent : BaseEvent {
  441. NVGcontext* vg;
  442. };
  443. virtual void onContextDestroy(const ContextDestroyEvent& e) {
  444. recurseEvent(&Widget::onContextDestroy, e);
  445. }
  446. };
  447. } // namespace widget
  448. /** Deprecated Rack v1 event namespace.
  449. Use events defined in the widget::Widget class instead of this `event::` namespace in new code.
  450. */
  451. namespace event {
  452. using Base = widget::BaseEvent;
  453. using PositionBase = widget::Widget::PositionBaseEvent;
  454. using KeyBase = widget::Widget::KeyBaseEvent;
  455. using TextBase = widget::Widget::TextBaseEvent;
  456. using Hover = widget::Widget::HoverEvent;
  457. using Button = widget::Widget::ButtonEvent;
  458. using DoubleClick = widget::Widget::DoubleClickEvent;
  459. using HoverKey = widget::Widget::HoverKeyEvent;
  460. using HoverText = widget::Widget::HoverTextEvent;
  461. using HoverScroll = widget::Widget::HoverScrollEvent;
  462. using Enter = widget::Widget::EnterEvent;
  463. using Leave = widget::Widget::LeaveEvent;
  464. using Select = widget::Widget::SelectEvent;
  465. using Deselect = widget::Widget::DeselectEvent;
  466. using SelectKey = widget::Widget::SelectKeyEvent;
  467. using SelectText = widget::Widget::SelectTextEvent;
  468. using DragBase = widget::Widget::DragBaseEvent;
  469. using DragStart = widget::Widget::DragStartEvent;
  470. using DragEnd = widget::Widget::DragEndEvent;
  471. using DragMove = widget::Widget::DragMoveEvent;
  472. using DragHover = widget::Widget::DragHoverEvent;
  473. using DragEnter = widget::Widget::DragEnterEvent;
  474. using DragLeave = widget::Widget::DragLeaveEvent;
  475. using DragDrop = widget::Widget::DragDropEvent;
  476. using PathDrop = widget::Widget::PathDropEvent;
  477. using Action = widget::Widget::ActionEvent;
  478. using Change = widget::Widget::ChangeEvent;
  479. using Dirty = widget::Widget::DirtyEvent;
  480. using Reposition = widget::Widget::RepositionEvent;
  481. using Resize = widget::Widget::ResizeEvent;
  482. using Add = widget::Widget::AddEvent;
  483. using Remove = widget::Widget::RemoveEvent;
  484. using Show = widget::Widget::ShowEvent;
  485. using Hide = widget::Widget::HideEvent;
  486. }
  487. } // namespace rack