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.

1620 lines
47KB

  1. /*
  2. OUI - A minimal semi-immediate GUI handling & layouting library
  3. Copyright (c) 2014 Leonard Ritter <leonard.ritter@duangle.com>
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. */
  20. #ifndef _OUI_H_
  21. #define _OUI_H_
  22. #ifdef __cplusplus
  23. extern "C" {
  24. #endif
  25. /*
  26. Revision 2 (2014-07-13)
  27. OUI (short for "Open UI", spoken like the french "oui" for "yes") is a
  28. platform agnostic single-header C library for layouting GUI elements and
  29. handling related user input. Together with a set of widget drawing and logic
  30. routines it can be used to build complex user interfaces.
  31. OUI is a semi-immediate GUI. Widget declarations are persistent for the duration
  32. of the setup and evaluation, but do not need to be kept around longer than one
  33. frame.
  34. OUI has no widget types; instead, it provides only one kind of element, "Items",
  35. which can be taylored to the application by the user and expanded with custom
  36. buffers and event handlers to behave as containers, buttons, sliders, radio
  37. buttons, and so on.
  38. OUI also does not draw anything; Instead it provides a set of functions to
  39. iterate and query the layouted items in order to allow client code to render
  40. each widget with its current state using a preferred graphics library.
  41. A basic setup for OUI usage looks like this:
  42. void app_main(...) {
  43. UIcontext *context = uiCreateContext();
  44. uiMakeCurrent(context);
  45. while (app_running()) {
  46. // update position of mouse cursor; the ui can also be updated
  47. // from received events.
  48. uiSetCursor(app_get_mouse_x(), app_get_mouse_y());
  49. // update button state
  50. for (int i = 0; i < 3; ++i)
  51. uiSetButton(i, app_get_button_state(i));
  52. // begin new UI declarations
  53. uiClear();
  54. // - UI setup code goes here -
  55. app_setup_ui();
  56. // layout UI
  57. uiLayout();
  58. // draw UI
  59. app_draw_ui(render_context,0,0,0);
  60. // update states and fire handlers
  61. uiProcess();
  62. }
  63. uiDestroyContext(context);
  64. }
  65. Here's an example setup for a checkbox control:
  66. typedef struct CheckBoxData {
  67. int type;
  68. const char *label;
  69. bool *checked;
  70. } CheckBoxData;
  71. // called when the item is clicked (see checkbox())
  72. void app_checkbox_handler(int item, UIevent event) {
  73. // retrieve custom data (see checkbox())
  74. const CheckBoxData *data = (const CheckBoxData *)uiGetData(item);
  75. // toggle value
  76. *data->checked = !(*data->checked);
  77. }
  78. // creates a checkbox control for a pointer to a boolean and attaches it to
  79. // a parent item.
  80. int checkbox(int parent, UIhandle handle, const char *label, bool *checked) {
  81. // create new ui item
  82. int item = uiItem();
  83. // set persistent handle for item that is used
  84. // to track activity over time
  85. uiSetHandle(item, handle);
  86. // set size of wiget; horizontal size is dynamic, vertical is fixed
  87. uiSetSize(item, 0, APP_WIDGET_HEIGHT);
  88. // attach checkbox handler, set to fire as soon as the left button is
  89. // pressed; UI_BUTTON0_HOT_UP is also a popular alternative.
  90. uiSetHandler(item, app_checkbox_handler, UI_BUTTON0_DOWN);
  91. // store some custom data with the checkbox that we use for rendering
  92. // and value changes.
  93. CheckBoxData *data = (CheckBoxData *)uiAllocData(item, sizeof(CheckBoxData));
  94. // assign a custom typeid to the data so the renderer knows how to
  95. // render this control.
  96. data->type = APP_WIDGET_CHECKBOX;
  97. data->label = label;
  98. data->checked = checked;
  99. // append to parent
  100. uiAppend(parent, item);
  101. return item;
  102. }
  103. A simple recursive drawing routine can look like this:
  104. void app_draw_ui(AppRenderContext *ctx, int item, int x, int y) {
  105. // retrieve custom data and cast it to an int; we assume the first member
  106. // of every widget data item to be an "int type" field.
  107. const int *type = (const int *)uiGetData(item);
  108. // get the widgets relative rectangle and offset by the parents
  109. // absolute position.
  110. UIrect rect = uiGetRect(item);
  111. rect.x += x;
  112. rect.y += y;
  113. // if a type is set, this is a specialized widget
  114. if (type) {
  115. switch(*type) {
  116. default: break;
  117. case APP_WIDGET_LABEL: {
  118. // ...
  119. } break;
  120. case APP_WIDGET_BUTTON: {
  121. // ...
  122. } break;
  123. case APP_WIDGET_CHECKBOX: {
  124. // cast to the full data type
  125. const CheckBoxData *data = (CheckBoxData*)type;
  126. // get the widgets current state
  127. int state = uiGetState(item);
  128. // if the value is set, the state is always active
  129. if (*data->checked)
  130. state = UI_ACTIVE;
  131. // draw the checkbox
  132. app_draw_checkbox(ctx, rect, state, data->label);
  133. } break;
  134. }
  135. }
  136. // iterate through all children and draw
  137. int kid = uiFirstChild(item);
  138. while (kid >= 0) {
  139. app_draw_ui(ctx, kid, rect.x, rect.y);
  140. kid = uiNextSibling(kid);
  141. }
  142. }
  143. See example.cpp in the repository for a full usage example.
  144. */
  145. // you can override this from the outside to pick
  146. // the export level you need
  147. #ifndef OUI_EXPORT
  148. #define OUI_EXPORT
  149. #endif
  150. // limits
  151. enum {
  152. // maximum number of items that may be added (must be power of 2)
  153. UI_MAX_ITEMS = 4096,
  154. // maximum size in bytes reserved for storage of application dependent data
  155. // as passed to uiAllocData().
  156. UI_MAX_BUFFERSIZE = 1048576,
  157. // maximum size in bytes of a single data buffer passed to uiAllocData().
  158. UI_MAX_DATASIZE = 4096,
  159. // maximum depth of nested containers
  160. UI_MAX_DEPTH = 64,
  161. // maximum number of buffered input events
  162. UI_MAX_INPUT_EVENTS = 64,
  163. // consecutive click threshold in ms
  164. UI_CLICK_THRESHOLD = 250,
  165. };
  166. typedef unsigned int UIuint;
  167. // opaque UI context
  168. typedef struct UIcontext UIcontext;
  169. // item states as returned by uiGetState()
  170. typedef enum UIitemState {
  171. // the item is inactive
  172. UI_COLD = 0,
  173. // the item is inactive, but the cursor is hovering over this item
  174. UI_HOT = 1,
  175. // the item is toggled, activated, focused (depends on item kind)
  176. UI_ACTIVE = 2,
  177. // the item is unresponsive
  178. UI_FROZEN = 3,
  179. } UIitemState;
  180. // container flags to pass to uiSetBox()
  181. typedef enum UIboxFlags {
  182. // flex-direction (bit 0+1)
  183. // left to right
  184. UI_ROW = 0x002,
  185. // top to bottom
  186. UI_COLUMN = 0x003,
  187. // model (bit 1)
  188. // free layout
  189. UI_LAYOUT = 0x000,
  190. // flex model
  191. UI_FLEX = 0x002,
  192. // flex-wrap (bit 2)
  193. // single-line
  194. UI_NOWRAP = 0x000,
  195. // multi-line, wrap left to right
  196. UI_WRAP = 0x004,
  197. // justify-content (start, end, center, space-between)
  198. // at start of row/column
  199. UI_START = 0x008,
  200. // at center of row/column
  201. UI_MIDDLE = 0x000,
  202. // at end of row/column
  203. UI_END = 0x010,
  204. // insert spacing to stretch across whole row/column
  205. UI_JUSTIFY = 0x018,
  206. // align-items
  207. // can be implemented by putting a flex container in a layout container,
  208. // then using UI_TOP, UI_DOWN, UI_VFILL, UI_VCENTER, etc.
  209. // FILL is equivalent to stretch/grow
  210. // align-content (start, end, center, stretch)
  211. // can be implemented by putting a flex container in a layout container,
  212. // then using UI_TOP, UI_DOWN, UI_VFILL, UI_VCENTER, etc.
  213. // FILL is equivalent to stretch; space-between is not supported.
  214. } UIboxFlags;
  215. // child layout flags to pass to uiSetLayout()
  216. typedef enum UIlayoutFlags {
  217. // attachments (bit 5-8)
  218. // fully valid when parent uses UI_LAYOUT model
  219. // partially valid when in UI_FLEX model
  220. // anchor to left item or left side of parent
  221. UI_LEFT = 0x020,
  222. // anchor to top item or top side of parent
  223. UI_TOP = 0x040,
  224. // anchor to right item or right side of parent
  225. UI_RIGHT = 0x080,
  226. // anchor to bottom item or bottom side of parent
  227. UI_DOWN = 0x100,
  228. // anchor to both left and right item or parent borders
  229. UI_HFILL = 0x0a0,
  230. // anchor to both top and bottom item or parent borders
  231. UI_VFILL = 0x140,
  232. // center horizontally, with left margin as offset
  233. UI_HCENTER = 0x000,
  234. // center vertically, with top margin as offset
  235. UI_VCENTER = 0x000,
  236. // center in both directions, with left/top margin as offset
  237. UI_CENTER = 0x000,
  238. // anchor to all four directions
  239. UI_FILL = 0x1e0,
  240. // when wrapping, put this element on a new line
  241. // wrapping layout code auto-inserts UI_BREAK flags,
  242. // drawing routines can read them with uiGetLayout()
  243. UI_BREAK = 0x200,
  244. } UIlayoutFlags;
  245. // event flags
  246. typedef enum UIevent {
  247. // on button 0 down
  248. UI_BUTTON0_DOWN = 0x0400,
  249. // on button 0 up
  250. // when this event has a handler, uiGetState() will return UI_ACTIVE as
  251. // long as button 0 is down.
  252. UI_BUTTON0_UP = 0x0800,
  253. // on button 0 up while item is hovered
  254. // when this event has a handler, uiGetState() will return UI_ACTIVE
  255. // when the cursor is hovering the items rectangle; this is the
  256. // behavior expected for buttons.
  257. UI_BUTTON0_HOT_UP = 0x1000,
  258. // item is being captured (button 0 constantly pressed);
  259. // when this event has a handler, uiGetState() will return UI_ACTIVE as
  260. // long as button 0 is down.
  261. UI_BUTTON0_CAPTURE = 0x2000,
  262. // on button 2 down (right mouse button, usually triggers context menu)
  263. UI_BUTTON2_DOWN = 0x4000,
  264. // item has received a scrollwheel event
  265. // the accumulated wheel offset can be queried with uiGetScroll()
  266. UI_SCROLL = 0x8000,
  267. // item is focused and has received a key-down event
  268. // the respective key can be queried using uiGetKey() and uiGetModifier()
  269. UI_KEY_DOWN = 0x10000,
  270. // item is focused and has received a key-up event
  271. // the respective key can be queried using uiGetKey() and uiGetModifier()
  272. UI_KEY_UP = 0x20000,
  273. // item is focused and has received a character event
  274. // the respective character can be queried using uiGetKey()
  275. UI_CHAR = 0x40000,
  276. } UIevent;
  277. // handler callback; event is one of UI_EVENT_*
  278. typedef void (*UIhandler)(int item, UIevent event);
  279. // for cursor positions, mainly
  280. typedef struct UIvec2 {
  281. union {
  282. int v[2];
  283. struct { int x, y; };
  284. };
  285. } UIvec2;
  286. // layout rectangle
  287. typedef struct UIrect {
  288. union {
  289. int v[4];
  290. struct { int x, y, w, h; };
  291. };
  292. } UIrect;
  293. // unless declared otherwise, all operations have the complexity O(1).
  294. // Context Management
  295. // ------------------
  296. // create a new UI context; call uiMakeCurrent() to make this context the
  297. // current context. The context is managed by the client and must be released
  298. // using uiDestroyContext()
  299. OUI_EXPORT UIcontext *uiCreateContext();
  300. // select an UI context as the current context; a context must always be
  301. // selected before using any of the other UI functions
  302. OUI_EXPORT void uiMakeCurrent(UIcontext *ctx);
  303. // release the memory of an UI context created with uiCreateContext(); if the
  304. // context is the current context, the current context will be set to NULL
  305. OUI_EXPORT void uiDestroyContext(UIcontext *ctx);
  306. // Input Control
  307. // -------------
  308. // sets the current cursor position (usually belonging to a mouse) to the
  309. // screen coordinates at (x,y)
  310. OUI_EXPORT void uiSetCursor(int x, int y);
  311. // returns the current cursor position in screen coordinates as set by
  312. // uiSetCursor()
  313. OUI_EXPORT UIvec2 uiGetCursor();
  314. // returns the offset of the cursor relative to the last call to uiProcess()
  315. OUI_EXPORT UIvec2 uiGetCursorDelta();
  316. // returns the beginning point of a drag operation.
  317. OUI_EXPORT UIvec2 uiGetCursorStart();
  318. // returns the offset of the cursor relative to the beginning point of a drag
  319. // operation.
  320. OUI_EXPORT UIvec2 uiGetCursorStartDelta();
  321. // sets a mouse or gamepad button as pressed/released
  322. // button is in the range 0..63 and maps to an application defined input
  323. // source.
  324. // enabled is 1 for pressed, 0 for released
  325. OUI_EXPORT void uiSetButton(int button, int enabled);
  326. // returns the current state of an application dependent input button
  327. // as set by uiSetButton().
  328. // the function returns 1 if the button has been set to pressed, 0 for released.
  329. OUI_EXPORT int uiGetButton(int button);
  330. // returns the number of chained clicks; 1 is a single click,
  331. // 2 is a double click, etc.
  332. OUI_EXPORT int uiGetClicks();
  333. // sets a key as down/up; the key can be any application defined keycode
  334. // mod is an application defined set of flags for modifier keys
  335. // enabled is 1 for key down, 0 for key up
  336. // all key events are being buffered until the next call to uiProcess()
  337. OUI_EXPORT void uiSetKey(unsigned int key, unsigned int mod, int enabled);
  338. // sends a single character for text input; the character is usually in the
  339. // unicode range, but can be application defined.
  340. // all char events are being buffered until the next call to uiProcess()
  341. OUI_EXPORT void uiSetChar(unsigned int value);
  342. // accumulates scroll wheel offsets for the current frame
  343. // all offsets are being accumulated until the next call to uiProcess()
  344. OUI_EXPORT void uiSetScroll(int x, int y);
  345. // returns the currently accumulated scroll wheel offsets for this frame
  346. OUI_EXPORT UIvec2 uiGetScroll();
  347. // Stages
  348. // ------
  349. // clear the item buffer; uiClear() should be called before the first
  350. // UI declaration for this frame to avoid concatenation of the same UI multiple
  351. // times.
  352. // After the call, all previously declared item IDs are invalid, and all
  353. // application dependent context data has been freed.
  354. OUI_EXPORT void uiClear();
  355. // layout all added items starting from the root item 0.
  356. // after calling uiLayout(), no further modifications to the item tree should
  357. // be done until the next call to uiClear().
  358. // It is safe to immediately draw the items after a call to uiLayout().
  359. // this is an O(N) operation for N = number of declared items.
  360. OUI_EXPORT void uiLayout();
  361. // update the current hot item; this only needs to be called if items are kept
  362. // for more than one frame and uiLayout() is not called
  363. OUI_EXPORT void uiUpdateHotItem();
  364. // update the internal state according to the current cursor position and
  365. // button states, and call all registered handlers.
  366. // timestamp is the time in milliseconds relative to the last call to uiProcess()
  367. // and is used to estimate the threshold for double-clicks
  368. // after calling uiProcess(), no further modifications to the item tree should
  369. // be done until the next call to uiClear().
  370. // Items should be drawn before a call to uiProcess()
  371. // this is an O(N) operation for N = number of declared items.
  372. OUI_EXPORT void uiProcess(int timestamp);
  373. // reset the currently stored hot/active etc. handles; this should be called when
  374. // a re-declaration of the UI changes the item indices, to avoid state
  375. // related glitches because item identities have changed.
  376. OUI_EXPORT void uiClearState();
  377. // UI Declaration
  378. // --------------
  379. // create a new UI item and return the new items ID.
  380. OUI_EXPORT int uiItem();
  381. // set an items state to frozen; the UI will not recurse into frozen items
  382. // when searching for hot or active items; subsequently, frozen items and
  383. // their child items will not cause mouse event notifications.
  384. // The frozen state is not applied recursively; uiGetState() will report
  385. // UI_COLD for child items. Upon encountering a frozen item, the drawing
  386. // routine needs to handle rendering of child items appropriately.
  387. // see example.cpp for a demonstration.
  388. OUI_EXPORT void uiSetFrozen(int item, int enable);
  389. // set the application-dependent handle of an item.
  390. // handle is an application defined 64-bit handle. If handle is NULL, the item
  391. // will not be interactive.
  392. OUI_EXPORT void uiSetHandle(int item, void *handle);
  393. // allocate space for application-dependent context data and assign it
  394. // as the handle to the item.
  395. // The memory of the pointer is managed by the UI context and released
  396. // upon the next call to uiClear()
  397. OUI_EXPORT void *uiAllocHandle(int item, int size);
  398. // set the global handler callback for interactive items.
  399. // the handler will be called for each item whose event flags are set using
  400. // uiSetEvents.
  401. OUI_EXPORT void uiSetHandler(UIhandler handler);
  402. // flags is a combination of UI_EVENT_* and designates for which events the
  403. // handler should be called.
  404. OUI_EXPORT void uiSetEvents(int item, int flags);
  405. // assign an item to a container.
  406. // an item ID of 0 refers to the root item.
  407. // the function returns the child item ID
  408. // if the container has already added items, the function searches
  409. // for the last item and calls uiInsert() on it, which is an
  410. // O(N) operation for N siblings.
  411. // it is usually more efficient to call uiAppend() for the first child,
  412. // then chain additional siblings using uiInsert().
  413. OUI_EXPORT int uiAppend(int item, int child);
  414. // assign an item to the same container as another item
  415. // sibling is inserted after item.
  416. OUI_EXPORT int uiInsert(int item, int sibling);
  417. // set the size of the item; a size of 0 indicates the dimension to be
  418. // dynamic; if the size is set, the item can not expand beyond that size.
  419. OUI_EXPORT void uiSetSize(int item, int w, int h);
  420. // set the anchoring behavior of the item to one or multiple UIlayoutFlags
  421. OUI_EXPORT void uiSetLayout(int item, int flags);
  422. // set the box model behavior of the item to one or multiple UIboxFlags
  423. OUI_EXPORT void uiSetBox(int item, int flags);
  424. // set the left, top, right and bottom margins of an item; when the item is
  425. // anchored to the parent or another item, the margin controls the distance
  426. // from the neighboring element.
  427. OUI_EXPORT void uiSetMargins(int item, short l, short t, short r, short b);
  428. // set item as recipient of all keyboard events; the item must have a handle
  429. // assigned; if item is -1, no item will be focused.
  430. OUI_EXPORT void uiFocus(int item);
  431. // Iteration
  432. // ---------
  433. // returns the first child item of a container item. If the item is not
  434. // a container or does not contain any items, -1 is returned.
  435. // if item is 0, the first child item of the root item will be returned.
  436. OUI_EXPORT int uiFirstChild(int item);
  437. // returns an items next sibling in the list of the parent containers children.
  438. // if item is 0 or the item is the last child item, -1 will be returned.
  439. OUI_EXPORT int uiNextSibling(int item);
  440. // Querying
  441. // --------
  442. // return the total number of allocated items
  443. OUI_EXPORT int uiGetItemCount();
  444. // return the current state of the item. This state is only valid after
  445. // a call to uiProcess().
  446. // The returned value is one of UI_COLD, UI_HOT, UI_ACTIVE, UI_FROZEN.
  447. OUI_EXPORT UIitemState uiGetState(int item);
  448. // return the application-dependent handle of the item as passed to uiSetHandle()
  449. // or uiAllocHandle().
  450. OUI_EXPORT void *uiGetHandle(int item);
  451. // return the item that is currently under the cursor or -1 for none
  452. OUI_EXPORT int uiGetHotItem();
  453. // return the item that is currently focused or -1 for none
  454. OUI_EXPORT int uiGetFocusedItem();
  455. // return the handler callback as passed to uiSetHandler()
  456. OUI_EXPORT UIhandler uiGetHandler();
  457. // return the event flags for an item as passed to uiSetEvents()
  458. OUI_EXPORT int uiGetEvents(int item);
  459. // when handling a KEY_DOWN/KEY_UP event: the key that triggered this event
  460. OUI_EXPORT unsigned int uiGetKey();
  461. // when handling a KEY_DOWN/KEY_UP event: the key that triggered this event
  462. OUI_EXPORT unsigned int uiGetModifier();
  463. // returns the items layout rectangle in absolute coordinates. If
  464. // uiGetRect() is called before uiLayout(), the values of the returned
  465. // rectangle are undefined.
  466. OUI_EXPORT UIrect uiGetRect(int item);
  467. // returns 1 if an items absolute rectangle contains a given coordinate
  468. // otherwise 0
  469. OUI_EXPORT int uiContains(int item, int x, int y);
  470. // return the width of the item as set by uiSetSize()
  471. OUI_EXPORT int uiGetWidth(int item);
  472. // return the height of the item as set by uiSetSize()
  473. OUI_EXPORT int uiGetHeight(int item);
  474. // return the anchoring behavior as set by uiSetLayout()
  475. OUI_EXPORT int uiGetLayout(int item);
  476. // return the box model as set by uiSetBox()
  477. OUI_EXPORT int uiGetBox(int item);
  478. // return the left margin of the item as set with uiSetMargins()
  479. OUI_EXPORT short uiGetMarginLeft(int item);
  480. // return the top margin of the item as set with uiSetMargins()
  481. OUI_EXPORT short uiGetMarginTop(int item);
  482. // return the right margin of the item as set with uiSetMargins()
  483. OUI_EXPORT short uiGetMarginRight(int item);
  484. // return the bottom margin of the item as set with uiSetMargins()
  485. OUI_EXPORT short uiGetMarginDown(int item);
  486. #ifdef __cplusplus
  487. };
  488. #endif
  489. #endif // _OUI_H_
  490. #ifdef OUI_IMPLEMENTATION
  491. #include <assert.h>
  492. #ifdef _MSC_VER
  493. #pragma warning (disable: 4996) // Switch off security warnings
  494. #pragma warning (disable: 4100) // Switch off unreferenced formal parameter warnings
  495. #ifdef __cplusplus
  496. #define UI_INLINE inline
  497. #else
  498. #define UI_INLINE
  499. #endif
  500. #else
  501. #define UI_INLINE inline
  502. #endif
  503. #define UI_MAX_KIND 16
  504. #define UI_ANY_BUTTON0_INPUT (UI_BUTTON0_DOWN \
  505. |UI_BUTTON0_UP \
  506. |UI_BUTTON0_HOT_UP \
  507. |UI_BUTTON0_CAPTURE)
  508. #define UI_ANY_BUTTON2_INPUT (UI_BUTTON2_DOWN)
  509. #define UI_ANY_MOUSE_INPUT (UI_ANY_BUTTON0_INPUT \
  510. |UI_ANY_BUTTON2_INPUT)
  511. #define UI_ANY_KEY_INPUT (UI_KEY_DOWN \
  512. |UI_KEY_UP \
  513. |UI_CHAR)
  514. #define UI_ANY_INPUT (UI_ANY_MOUSE_INPUT \
  515. |UI_ANY_KEY_INPUT)
  516. // extra item flags
  517. enum {
  518. // bit 0-2
  519. UI_ITEM_BOX_MODEL_MASK = 0x000007,
  520. // bit 0-4
  521. UI_ITEM_BOX_MASK = 0x00001F,
  522. // bit 5-8
  523. UI_ITEM_LAYOUT_MASK = 0x0003E0,
  524. // bit 9-18
  525. UI_ITEM_EVENT_MASK = 0x07FC00,
  526. // item is frozen (bit 19)
  527. UI_ITEM_FROZEN = 0x080000,
  528. // item handle is pointer to data (bit 20)
  529. UI_ITEM_DATA = 0x100000,
  530. // item has been inserted
  531. UI_ITEM_INSERTED = 0x200000,
  532. };
  533. typedef struct UIitem {
  534. // data handle
  535. void *handle;
  536. // about 27 bits worth of flags
  537. unsigned int flags;
  538. // index of first kid
  539. int firstkid;
  540. // index of next sibling with same parent
  541. int nextitem;
  542. // margin offsets, interpretation depends on flags
  543. // after layouting, the first two components are absolute coordinates
  544. short margins[4];
  545. // size
  546. short size[2];
  547. } UIitem;
  548. typedef enum UIstate {
  549. UI_STATE_IDLE = 0,
  550. UI_STATE_CAPTURE,
  551. } UIstate;
  552. typedef struct UIhandleEntry {
  553. unsigned int key;
  554. int item;
  555. } UIhandleEntry;
  556. typedef struct UIinputEvent {
  557. unsigned int key;
  558. unsigned int mod;
  559. UIevent event;
  560. } UIinputEvent;
  561. struct UIcontext {
  562. // handler
  563. UIhandler handler;
  564. // button state in this frame
  565. unsigned long long buttons;
  566. // button state in the previous frame
  567. unsigned long long last_buttons;
  568. // where the cursor was at the beginning of the active state
  569. UIvec2 start_cursor;
  570. // where the cursor was last frame
  571. UIvec2 last_cursor;
  572. // where the cursor is currently
  573. UIvec2 cursor;
  574. // accumulated scroll wheel offsets
  575. UIvec2 scroll;
  576. int active_item;
  577. int focus_item;
  578. int last_hot_item;
  579. int last_click_item;
  580. int hot_item;
  581. UIstate state;
  582. unsigned int active_key;
  583. unsigned int active_modifier;
  584. int event_item;
  585. int last_timestamp;
  586. int last_click_timestamp;
  587. int clicks;
  588. int count;
  589. int datasize;
  590. int eventcount;
  591. UIitem items[UI_MAX_ITEMS];
  592. unsigned char data[UI_MAX_BUFFERSIZE];
  593. UIinputEvent events[UI_MAX_INPUT_EVENTS];
  594. };
  595. UI_INLINE int ui_max(int a, int b) {
  596. return (a>b)?a:b;
  597. }
  598. UI_INLINE int ui_min(int a, int b) {
  599. return (a<b)?a:b;
  600. }
  601. static UIcontext *ui_context = NULL;
  602. UIcontext *uiCreateContext() {
  603. UIcontext *ctx = (UIcontext *)malloc(sizeof(UIcontext));
  604. memset(ctx, 0, sizeof(UIcontext));
  605. UIcontext *oldctx = ui_context;
  606. uiMakeCurrent(ctx);
  607. uiClear();
  608. uiClearState();
  609. uiMakeCurrent(oldctx);
  610. return ctx;
  611. }
  612. void uiMakeCurrent(UIcontext *ctx) {
  613. ui_context = ctx;
  614. }
  615. void uiDestroyContext(UIcontext *ctx) {
  616. if (ui_context == ctx)
  617. uiMakeCurrent(NULL);
  618. free(ctx);
  619. }
  620. void uiSetButton(int button, int enabled) {
  621. assert(ui_context);
  622. unsigned long long mask = 1ull<<button;
  623. // set new bit
  624. ui_context->buttons = (enabled)?
  625. (ui_context->buttons | mask):
  626. (ui_context->buttons & ~mask);
  627. }
  628. static void uiAddInputEvent(UIinputEvent event) {
  629. assert(ui_context);
  630. if (ui_context->eventcount == UI_MAX_INPUT_EVENTS) return;
  631. ui_context->events[ui_context->eventcount++] = event;
  632. }
  633. static void uiClearInputEvents() {
  634. assert(ui_context);
  635. ui_context->eventcount = 0;
  636. ui_context->scroll.x = 0;
  637. ui_context->scroll.y = 0;
  638. }
  639. void uiSetKey(unsigned int key, unsigned int mod, int enabled) {
  640. assert(ui_context);
  641. UIinputEvent event = { key, mod, enabled?UI_KEY_DOWN:UI_KEY_UP };
  642. uiAddInputEvent(event);
  643. }
  644. void uiSetChar(unsigned int value) {
  645. assert(ui_context);
  646. UIinputEvent event = { value, 0, UI_CHAR };
  647. uiAddInputEvent(event);
  648. }
  649. void uiSetScroll(int x, int y) {
  650. assert(ui_context);
  651. ui_context->scroll.x += x;
  652. ui_context->scroll.y += y;
  653. }
  654. UIvec2 uiGetScroll() {
  655. assert(ui_context);
  656. return ui_context->scroll;
  657. }
  658. int uiGetLastButton(int button) {
  659. assert(ui_context);
  660. return (ui_context->last_buttons & (1ull<<button))?1:0;
  661. }
  662. int uiGetButton(int button) {
  663. assert(ui_context);
  664. return (ui_context->buttons & (1ull<<button))?1:0;
  665. }
  666. int uiButtonPressed(int button) {
  667. assert(ui_context);
  668. return !uiGetLastButton(button) && uiGetButton(button);
  669. }
  670. int uiButtonReleased(int button) {
  671. assert(ui_context);
  672. return uiGetLastButton(button) && !uiGetButton(button);
  673. }
  674. void uiSetCursor(int x, int y) {
  675. assert(ui_context);
  676. ui_context->cursor.x = x;
  677. ui_context->cursor.y = y;
  678. }
  679. UIvec2 uiGetCursor() {
  680. assert(ui_context);
  681. return ui_context->cursor;
  682. }
  683. UIvec2 uiGetCursorStart() {
  684. assert(ui_context);
  685. return ui_context->start_cursor;
  686. }
  687. UIvec2 uiGetCursorDelta() {
  688. assert(ui_context);
  689. UIvec2 result = {{{
  690. ui_context->cursor.x - ui_context->last_cursor.x,
  691. ui_context->cursor.y - ui_context->last_cursor.y
  692. }}};
  693. return result;
  694. }
  695. UIvec2 uiGetCursorStartDelta() {
  696. assert(ui_context);
  697. UIvec2 result = {{{
  698. ui_context->cursor.x - ui_context->start_cursor.x,
  699. ui_context->cursor.y - ui_context->start_cursor.y
  700. }}};
  701. return result;
  702. }
  703. unsigned int uiGetKey() {
  704. assert(ui_context);
  705. return ui_context->active_key;
  706. }
  707. unsigned int uiGetModifier() {
  708. assert(ui_context);
  709. return ui_context->active_modifier;
  710. }
  711. // return the total number of allocated items
  712. OUI_EXPORT int uiGetItemCount() {
  713. assert(ui_context);
  714. return ui_context->count;
  715. }
  716. UIitem *uiItemPtr(int item) {
  717. assert(ui_context && (item >= 0) && (item < ui_context->count));
  718. return ui_context->items + item;
  719. }
  720. int uiGetHotItem() {
  721. assert(ui_context);
  722. return ui_context->hot_item;
  723. }
  724. void uiFocus(int item) {
  725. assert(ui_context && (item >= -1) && (item < ui_context->count));
  726. ui_context->focus_item = item;
  727. }
  728. static void uiValidateStateItems() {
  729. assert(ui_context);
  730. if (ui_context->last_hot_item >= ui_context->count)
  731. ui_context->last_hot_item = -1;
  732. if (ui_context->active_item >= ui_context->count)
  733. ui_context->active_item = -1;
  734. if (ui_context->focus_item >= ui_context->count)
  735. ui_context->focus_item = -1;
  736. if (ui_context->last_click_item >= ui_context->count)
  737. ui_context->last_click_item = -1;
  738. }
  739. int uiGetFocusedItem() {
  740. assert(ui_context);
  741. return ui_context->focus_item;
  742. }
  743. void uiClear() {
  744. assert(ui_context);
  745. ui_context->count = 0;
  746. ui_context->datasize = 0;
  747. ui_context->hot_item = -1;
  748. }
  749. void uiClearState() {
  750. assert(ui_context);
  751. ui_context->last_hot_item = -1;
  752. ui_context->active_item = -1;
  753. ui_context->focus_item = -1;
  754. ui_context->last_click_item = -1;
  755. }
  756. int uiItem() {
  757. assert(ui_context);
  758. assert(ui_context->count < UI_MAX_ITEMS);
  759. int idx = ui_context->count++;
  760. UIitem *item = uiItemPtr(idx);
  761. memset(item, 0, sizeof(UIitem));
  762. item->firstkid = -1;
  763. item->nextitem = -1;
  764. return idx;
  765. }
  766. void uiNotifyItem(int item, UIevent event) {
  767. assert(ui_context);
  768. if (!ui_context->handler)
  769. return;
  770. assert((event & UI_ITEM_EVENT_MASK) == event);
  771. ui_context->event_item = item;
  772. UIitem *pitem = uiItemPtr(item);
  773. if (pitem->flags & event) {
  774. ui_context->handler(item, event);
  775. }
  776. }
  777. UI_INLINE int uiLastChild(int item) {
  778. item = uiFirstChild(item);
  779. if (item < 0)
  780. return -1;
  781. while (true) {
  782. int nextitem = uiNextSibling(item);
  783. if (nextitem < 0)
  784. return item;
  785. item = nextitem;
  786. }
  787. }
  788. int uiInsert(int item, int sibling) {
  789. assert(sibling > 0);
  790. UIitem *pitem = uiItemPtr(item);
  791. UIitem *psibling = uiItemPtr(sibling);
  792. assert(!(psibling->flags & UI_ITEM_INSERTED));
  793. psibling->nextitem = pitem->nextitem;
  794. psibling->flags |= UI_ITEM_INSERTED;
  795. pitem->nextitem = sibling;
  796. return sibling;
  797. }
  798. int uiAppend(int item, int child) {
  799. assert(child > 0);
  800. UIitem *pparent = uiItemPtr(item);
  801. UIitem *pchild = uiItemPtr(child);
  802. assert(!(pchild->flags & UI_ITEM_INSERTED));
  803. if (pparent->firstkid < 0) {
  804. pparent->firstkid = child;
  805. pchild->flags |= UI_ITEM_INSERTED;
  806. } else {
  807. uiInsert(uiLastChild(item), child);
  808. }
  809. return child;
  810. }
  811. void uiSetFrozen(int item, int enable) {
  812. UIitem *pitem = uiItemPtr(item);
  813. if (enable)
  814. pitem->flags |= UI_ITEM_FROZEN;
  815. else
  816. pitem->flags &= ~UI_ITEM_FROZEN;
  817. }
  818. void uiSetSize(int item, int w, int h) {
  819. UIitem *pitem = uiItemPtr(item);
  820. pitem->size[0] = w;
  821. pitem->size[1] = h;
  822. }
  823. int uiGetWidth(int item) {
  824. return uiItemPtr(item)->size[0];
  825. }
  826. int uiGetHeight(int item) {
  827. return uiItemPtr(item)->size[1];
  828. }
  829. void uiSetLayout(int item, int flags) {
  830. UIitem *pitem = uiItemPtr(item);
  831. assert((flags & UI_ITEM_LAYOUT_MASK) == flags);
  832. pitem->flags &= ~UI_ITEM_LAYOUT_MASK;
  833. pitem->flags |= flags & UI_ITEM_LAYOUT_MASK;
  834. }
  835. int uiGetLayout(int item) {
  836. return uiItemPtr(item)->flags & UI_ITEM_LAYOUT_MASK;
  837. }
  838. void uiSetBox(int item, int flags) {
  839. UIitem *pitem = uiItemPtr(item);
  840. assert((flags & UI_ITEM_BOX_MASK) == flags);
  841. pitem->flags &= ~UI_ITEM_BOX_MASK;
  842. pitem->flags |= flags & UI_ITEM_BOX_MASK;
  843. }
  844. int uiGetBox(int item) {
  845. return uiItemPtr(item)->flags & UI_ITEM_BOX_MASK;
  846. }
  847. void uiSetMargins(int item, short l, short t, short r, short b) {
  848. UIitem *pitem = uiItemPtr(item);
  849. pitem->margins[0] = l;
  850. pitem->margins[1] = t;
  851. pitem->margins[2] = r;
  852. pitem->margins[3] = b;
  853. }
  854. short uiGetMarginLeft(int item) {
  855. return uiItemPtr(item)->margins[0];
  856. }
  857. short uiGetMarginTop(int item) {
  858. return uiItemPtr(item)->margins[1];
  859. }
  860. short uiGetMarginRight(int item) {
  861. return uiItemPtr(item)->margins[2];
  862. }
  863. short uiGetMarginDown(int item) {
  864. return uiItemPtr(item)->margins[3];
  865. }
  866. // compute bounding box of all items super-imposed
  867. UI_INLINE void uiComputeImposedSize(UIitem *pitem, int dim) {
  868. int wdim = dim+2;
  869. // largest size is required size
  870. short need_size = 0;
  871. int kid = pitem->firstkid;
  872. while (kid >= 0) {
  873. UIitem *pkid = uiItemPtr(kid);
  874. // width = start margin + calculated width + end margin
  875. int kidsize = pkid->margins[dim] + pkid->size[dim] + pkid->margins[wdim];
  876. need_size = ui_max(need_size, kidsize);
  877. kid = uiNextSibling(kid);
  878. }
  879. pitem->size[dim] = need_size;
  880. }
  881. // compute bounding box of all items stacked
  882. UI_INLINE void uiComputeStackedSize(UIitem *pitem, int dim) {
  883. int wdim = dim+2;
  884. short need_size = 0;
  885. int kid = pitem->firstkid;
  886. while (kid >= 0) {
  887. UIitem *pkid = uiItemPtr(kid);
  888. // width += start margin + calculated width + end margin
  889. need_size += pkid->margins[dim] + pkid->size[dim] + pkid->margins[wdim];
  890. kid = uiNextSibling(kid);
  891. }
  892. pitem->size[dim] = need_size;
  893. }
  894. // compute bounding box of all items stacked + wrapped
  895. UI_INLINE void uiComputeWrappedSize(UIitem *pitem, int dim) {
  896. int wdim = dim+2;
  897. short need_size = 0;
  898. short need_size2 = 0;
  899. int kid = pitem->firstkid;
  900. while (kid >= 0) {
  901. UIitem *pkid = uiItemPtr(kid);
  902. // if next position moved back, we assume a new line
  903. if (pkid->flags & UI_BREAK) {
  904. need_size2 += need_size;
  905. // newline
  906. need_size = 0;
  907. }
  908. // width = start margin + calculated width + end margin
  909. int kidsize = pkid->margins[dim] + pkid->size[dim] + pkid->margins[wdim];
  910. need_size = ui_max(need_size, kidsize);
  911. kid = uiNextSibling(kid);
  912. }
  913. pitem->size[dim] = need_size2 + need_size;
  914. }
  915. static void uiComputeSize(int item, int dim) {
  916. UIitem *pitem = uiItemPtr(item);
  917. // children expand the size
  918. int kid = pitem->firstkid;
  919. while (kid >= 0) {
  920. uiComputeSize(kid, dim);
  921. kid = uiNextSibling(kid);
  922. }
  923. if (pitem->size[dim])
  924. return;
  925. switch(pitem->flags & UI_ITEM_BOX_MODEL_MASK) {
  926. case UI_COLUMN|UI_WRAP: {
  927. // flex model
  928. if (dim) // direction
  929. uiComputeStackedSize(pitem, 1);
  930. else
  931. uiComputeImposedSize(pitem, 0);
  932. } break;
  933. case UI_ROW|UI_WRAP: {
  934. // flex model
  935. if (!dim) // direction
  936. uiComputeStackedSize(pitem, 0);
  937. else
  938. uiComputeWrappedSize(pitem, 1);
  939. } break;
  940. case UI_COLUMN:
  941. case UI_ROW: {
  942. // flex model
  943. if ((pitem->flags & 1) == (unsigned int)dim) // direction
  944. uiComputeStackedSize(pitem, dim);
  945. else
  946. uiComputeImposedSize(pitem, dim);
  947. } break;
  948. default: {
  949. // layout model
  950. uiComputeImposedSize(pitem, dim);
  951. } break;
  952. }
  953. }
  954. // stack all items according to their alignment
  955. UI_INLINE void uiArrangeStacked(UIitem *pitem, int dim, bool wrap) {
  956. int wdim = dim+2;
  957. short space = pitem->size[dim];
  958. int start_kid = pitem->firstkid;
  959. while (start_kid >= 0) {
  960. short used = 0;
  961. int count = 0;
  962. int total = 0;
  963. bool hardbreak = false;
  964. // first pass: count items that need to be expanded,
  965. // and the space that is used
  966. int kid = start_kid;
  967. int end_kid = -1;
  968. while (kid >= 0) {
  969. UIitem *pkid = uiItemPtr(kid);
  970. int flags = (pkid->flags & UI_ITEM_LAYOUT_MASK) >> dim;
  971. short extend = used;
  972. if ((flags & UI_HFILL) == UI_HFILL) { // grow
  973. count++;
  974. extend += pkid->margins[dim] + pkid->margins[wdim];
  975. } else {
  976. extend += pkid->margins[dim] + pkid->size[dim] + pkid->margins[wdim];
  977. }
  978. // wrap on end of line or manual flag
  979. if (wrap && (total && ((extend > space) || (pkid->flags & UI_BREAK)))) {
  980. end_kid = kid;
  981. hardbreak = ((pkid->flags & UI_BREAK) == UI_BREAK);
  982. // add marker for subsequent queries
  983. pkid->flags |= UI_BREAK;
  984. break;
  985. } else {
  986. used = extend;
  987. kid = uiNextSibling(kid);
  988. }
  989. total++;
  990. }
  991. int extra_space = ui_max(space - used,0);
  992. float filler = 0.0f;
  993. float spacer = 0.0f;
  994. float extra_margin = 0.0f;
  995. if (extra_space) {
  996. if (count) {
  997. filler = (float)extra_space / (float)count;
  998. } else if (total) {
  999. switch(pitem->flags & UI_JUSTIFY) {
  1000. default: {
  1001. extra_margin = extra_space / 2.0f;
  1002. } break;
  1003. case UI_JUSTIFY: {
  1004. // justify when not wrapping or not in last line,
  1005. // or not manually breaking
  1006. if (!wrap || ((end_kid != -1) && !hardbreak))
  1007. spacer = (float)extra_space / (float)(total-1);
  1008. } break;
  1009. case UI_START: {
  1010. } break;
  1011. case UI_END: {
  1012. extra_margin = extra_space;
  1013. } break;
  1014. }
  1015. }
  1016. }
  1017. // distribute width among items
  1018. float x = (float)pitem->margins[dim];
  1019. float x1;
  1020. // second pass: distribute and rescale
  1021. kid = start_kid;
  1022. while (kid != end_kid) {
  1023. short ix0,ix1;
  1024. UIitem *pkid = uiItemPtr(kid);
  1025. int flags = (pkid->flags & UI_ITEM_LAYOUT_MASK) >> dim;
  1026. x += (float)pkid->margins[dim] + extra_margin;
  1027. if ((flags & UI_HFILL) == UI_HFILL) { // grow
  1028. x1 = x+filler;
  1029. } else {
  1030. x1 = x+(float)pkid->size[dim];
  1031. }
  1032. ix0 = (short)x;
  1033. ix1 = (short)x1;
  1034. pkid->margins[dim] = ix0;
  1035. pkid->size[dim] = ix1-ix0;
  1036. x = x1 + (float)pkid->margins[wdim];
  1037. kid = uiNextSibling(kid);
  1038. extra_margin = spacer;
  1039. }
  1040. start_kid = end_kid;
  1041. }
  1042. }
  1043. // superimpose all items according to their alignment
  1044. UI_INLINE void uiArrangeImposedRange(UIitem *pitem, int dim,
  1045. int start_kid, int end_kid, short offset, short space) {
  1046. int wdim = dim+2;
  1047. int kid = start_kid;
  1048. while (kid != end_kid) {
  1049. UIitem *pkid = uiItemPtr(kid);
  1050. int flags = (pkid->flags & UI_ITEM_LAYOUT_MASK) >> dim;
  1051. switch(flags & UI_HFILL) {
  1052. default: break;
  1053. case UI_HCENTER: {
  1054. pkid->margins[dim] += (space-pkid->size[dim])/2 - pkid->margins[wdim];
  1055. } break;
  1056. case UI_RIGHT: {
  1057. pkid->margins[dim] = space-pkid->size[dim]-pkid->margins[wdim];
  1058. } break;
  1059. case UI_HFILL: {
  1060. pkid->size[dim] = ui_max(0,space-pkid->margins[dim]-pkid->margins[wdim]);
  1061. } break;
  1062. }
  1063. pkid->margins[dim] += offset;
  1064. kid = uiNextSibling(kid);
  1065. }
  1066. }
  1067. UI_INLINE void uiArrangeImposed(UIitem *pitem, int dim) {
  1068. uiArrangeImposedRange(pitem, dim, pitem->firstkid, -1, pitem->margins[dim], pitem->size[dim]);
  1069. }
  1070. // superimpose all items according to their alignment
  1071. UI_INLINE short uiArrangeWrappedImposed(UIitem *pitem, int dim) {
  1072. int wdim = dim+2;
  1073. short offset = pitem->margins[dim];
  1074. short need_size = 0;
  1075. int kid = pitem->firstkid;
  1076. int start_kid = kid;
  1077. while (kid >= 0) {
  1078. UIitem *pkid = uiItemPtr(kid);
  1079. if (pkid->flags & UI_BREAK) {
  1080. uiArrangeImposedRange(pitem, dim, start_kid, kid, offset, need_size);
  1081. offset += need_size;
  1082. start_kid = kid;
  1083. // newline
  1084. need_size = 0;
  1085. }
  1086. // width = start margin + calculated width + end margin
  1087. int kidsize = pkid->margins[dim] + pkid->size[dim] + pkid->margins[wdim];
  1088. need_size = ui_max(need_size, kidsize);
  1089. kid = uiNextSibling(kid);
  1090. }
  1091. uiArrangeImposedRange(pitem, dim, start_kid, -1, offset, need_size);
  1092. offset += need_size;
  1093. return offset;
  1094. }
  1095. static void uiArrange(int item, int dim) {
  1096. UIitem *pitem = uiItemPtr(item);
  1097. switch(pitem->flags & UI_ITEM_BOX_MODEL_MASK) {
  1098. case UI_COLUMN|UI_WRAP: {
  1099. // flex model, wrapping
  1100. if (dim) { // direction
  1101. uiArrangeStacked(pitem, 1, true);
  1102. // this retroactive resize will not effect parent widths
  1103. short offset = uiArrangeWrappedImposed(pitem, 0);
  1104. pitem->size[0] = offset - pitem->margins[0];
  1105. }
  1106. } break;
  1107. case UI_ROW|UI_WRAP: {
  1108. // flex model, wrapping
  1109. if (!dim) { // direction
  1110. uiArrangeStacked(pitem, 0, true);
  1111. } else {
  1112. uiArrangeWrappedImposed(pitem, 1);
  1113. }
  1114. } break;
  1115. case UI_COLUMN:
  1116. case UI_ROW: {
  1117. // flex model
  1118. if ((pitem->flags & 1) == (unsigned int)dim) // direction
  1119. uiArrangeStacked(pitem, dim, false);
  1120. else
  1121. uiArrangeImposed(pitem, dim);
  1122. } break;
  1123. default: {
  1124. // layout model
  1125. uiArrangeImposed(pitem, dim);
  1126. } break;
  1127. }
  1128. int kid = uiFirstChild(item);
  1129. while (kid >= 0) {
  1130. uiArrange(kid, dim);
  1131. kid = uiNextSibling(kid);
  1132. }
  1133. }
  1134. void uiLayout() {
  1135. assert(ui_context);
  1136. if (!ui_context->count) return;
  1137. uiComputeSize(0,0);
  1138. uiArrange(0,0);
  1139. uiComputeSize(0,1);
  1140. uiArrange(0,1);
  1141. uiValidateStateItems();
  1142. // drawing routines may require this to be set already
  1143. uiUpdateHotItem();
  1144. }
  1145. UIrect uiGetRect(int item) {
  1146. UIitem *pitem = uiItemPtr(item);
  1147. UIrect rc = {{{
  1148. pitem->margins[0], pitem->margins[1],
  1149. pitem->size[0], pitem->size[1]
  1150. }}};
  1151. return rc;
  1152. }
  1153. int uiFirstChild(int item) {
  1154. return uiItemPtr(item)->firstkid;
  1155. }
  1156. int uiNextSibling(int item) {
  1157. return uiItemPtr(item)->nextitem;
  1158. }
  1159. void *uiAllocHandle(int item, int size) {
  1160. assert((size > 0) && (size < UI_MAX_DATASIZE));
  1161. UIitem *pitem = uiItemPtr(item);
  1162. assert(pitem->handle == NULL);
  1163. assert((ui_context->datasize+size) <= UI_MAX_BUFFERSIZE);
  1164. pitem->handle = ui_context->data + ui_context->datasize;
  1165. pitem->flags |= UI_ITEM_DATA;
  1166. ui_context->datasize += size;
  1167. return pitem->handle;
  1168. }
  1169. void uiSetHandle(int item, void *handle) {
  1170. UIitem *pitem = uiItemPtr(item);
  1171. assert(pitem->handle == NULL);
  1172. pitem->handle = handle;
  1173. }
  1174. void *uiGetHandle(int item) {
  1175. return uiItemPtr(item)->handle;
  1176. }
  1177. void uiSetHandler(UIhandler handler) {
  1178. assert(ui_context);
  1179. ui_context->handler = handler;
  1180. }
  1181. UIhandler uiGetHandler() {
  1182. assert(ui_context);
  1183. return ui_context->handler;
  1184. }
  1185. void uiSetEvents(int item, int flags) {
  1186. UIitem *pitem = uiItemPtr(item);
  1187. pitem->flags &= ~UI_ITEM_EVENT_MASK;
  1188. pitem->flags |= flags & UI_ITEM_EVENT_MASK;
  1189. }
  1190. int uiGetEvents(int item) {
  1191. return uiItemPtr(item)->flags & UI_ITEM_EVENT_MASK;
  1192. }
  1193. int uiContains(int item, int x, int y) {
  1194. UIrect rect = uiGetRect(item);
  1195. x -= rect.x;
  1196. y -= rect.y;
  1197. if ((x>=0)
  1198. && (y>=0)
  1199. && (x<rect.w)
  1200. && (y<rect.h)) return 1;
  1201. return 0;
  1202. }
  1203. int uiFindItemForEvent(int item, UIevent event, int x, int y) {
  1204. UIitem *pitem = uiItemPtr(item);
  1205. if (pitem->flags & UI_ITEM_FROZEN) return -1;
  1206. if (uiContains(item, x, y)) {
  1207. int best_hit = -1;
  1208. int kid = uiFirstChild(item);
  1209. while (kid >= 0) {
  1210. int hit = uiFindItemForEvent(kid, event, x, y);
  1211. if (hit >= 0) {
  1212. best_hit = hit;
  1213. }
  1214. kid = uiNextSibling(kid);
  1215. }
  1216. if (best_hit >= 0) {
  1217. return best_hit;
  1218. }
  1219. // click-through if the item has no handler for this event
  1220. if (pitem->flags & event) {
  1221. return item;
  1222. }
  1223. }
  1224. return -1;
  1225. }
  1226. void uiUpdateHotItem() {
  1227. assert(ui_context);
  1228. if (!ui_context->count) return;
  1229. ui_context->hot_item = uiFindItemForEvent(0,
  1230. (UIevent)UI_ANY_MOUSE_INPUT,
  1231. ui_context->cursor.x, ui_context->cursor.y);
  1232. }
  1233. int uiGetClicks() {
  1234. return ui_context->clicks;
  1235. }
  1236. void uiProcess(int timestamp) {
  1237. assert(ui_context);
  1238. if (!ui_context->count) {
  1239. uiClearInputEvents();
  1240. return;
  1241. }
  1242. int hot_item = ui_context->last_hot_item;
  1243. int active_item = ui_context->active_item;
  1244. int focus_item = ui_context->focus_item;
  1245. // send all keyboard events
  1246. if (focus_item >= 0) {
  1247. for (int i = 0; i < ui_context->eventcount; ++i) {
  1248. ui_context->active_key = ui_context->events[i].key;
  1249. ui_context->active_modifier = ui_context->events[i].mod;
  1250. uiNotifyItem(focus_item,
  1251. ui_context->events[i].event);
  1252. }
  1253. } else {
  1254. ui_context->focus_item = -1;
  1255. }
  1256. if (ui_context->scroll.x || ui_context->scroll.y) {
  1257. int scroll_item = uiFindItemForEvent(0, UI_SCROLL,
  1258. ui_context->cursor.x, ui_context->cursor.y);
  1259. if (scroll_item >= 0) {
  1260. uiNotifyItem(scroll_item, UI_SCROLL);
  1261. }
  1262. }
  1263. uiClearInputEvents();
  1264. int hot = ui_context->hot_item;
  1265. switch(ui_context->state) {
  1266. default:
  1267. case UI_STATE_IDLE: {
  1268. ui_context->start_cursor = ui_context->cursor;
  1269. if (uiGetButton(0)) {
  1270. hot_item = -1;
  1271. active_item = hot;
  1272. if (active_item != focus_item) {
  1273. focus_item = -1;
  1274. ui_context->focus_item = -1;
  1275. }
  1276. if (active_item >= 0) {
  1277. if (
  1278. ((timestamp - ui_context->last_click_timestamp) > UI_CLICK_THRESHOLD)
  1279. || (ui_context->last_click_item != active_item)) {
  1280. ui_context->clicks = 0;
  1281. }
  1282. ui_context->clicks++;
  1283. ui_context->last_click_timestamp = timestamp;
  1284. ui_context->last_click_item = active_item;
  1285. uiNotifyItem(active_item, UI_BUTTON0_DOWN);
  1286. }
  1287. ui_context->state = UI_STATE_CAPTURE;
  1288. } else if (uiGetButton(2) && !uiGetLastButton(2)) {
  1289. hot_item = -1;
  1290. hot = uiFindItemForEvent(0, UI_BUTTON2_DOWN,
  1291. ui_context->cursor.x, ui_context->cursor.y);
  1292. if (hot >= 0) {
  1293. uiNotifyItem(hot, UI_BUTTON2_DOWN);
  1294. }
  1295. } else {
  1296. hot_item = hot;
  1297. }
  1298. } break;
  1299. case UI_STATE_CAPTURE: {
  1300. if (!uiGetButton(0)) {
  1301. if (active_item >= 0) {
  1302. uiNotifyItem(active_item, UI_BUTTON0_UP);
  1303. if (active_item == hot) {
  1304. uiNotifyItem(active_item, UI_BUTTON0_HOT_UP);
  1305. }
  1306. }
  1307. active_item = -1;
  1308. ui_context->state = UI_STATE_IDLE;
  1309. } else {
  1310. if (active_item >= 0) {
  1311. uiNotifyItem(active_item, UI_BUTTON0_CAPTURE);
  1312. }
  1313. if (hot == active_item)
  1314. hot_item = hot;
  1315. else
  1316. hot_item = -1;
  1317. }
  1318. } break;
  1319. }
  1320. ui_context->last_cursor = ui_context->cursor;
  1321. ui_context->last_hot_item = hot_item;
  1322. ui_context->active_item = active_item;
  1323. ui_context->last_timestamp = timestamp;
  1324. ui_context->last_buttons = ui_context->buttons;
  1325. }
  1326. static int uiIsActive(int item) {
  1327. assert(ui_context);
  1328. return ui_context->active_item == item;
  1329. }
  1330. static int uiIsHot(int item) {
  1331. assert(ui_context);
  1332. return ui_context->last_hot_item == item;
  1333. }
  1334. static int uiIsFocused(int item) {
  1335. assert(ui_context);
  1336. return ui_context->focus_item == item;
  1337. }
  1338. UIitemState uiGetState(int item) {
  1339. UIitem *pitem = uiItemPtr(item);
  1340. if (pitem->flags & UI_ITEM_FROZEN) return UI_FROZEN;
  1341. if (uiIsFocused(item)) {
  1342. if (pitem->flags & (UI_KEY_DOWN|UI_CHAR|UI_KEY_UP)) return UI_ACTIVE;
  1343. }
  1344. if (uiIsActive(item)) {
  1345. if (pitem->flags & (UI_BUTTON0_CAPTURE|UI_BUTTON0_UP)) return UI_ACTIVE;
  1346. if ((pitem->flags & UI_BUTTON0_HOT_UP)
  1347. && uiIsHot(item)) return UI_ACTIVE;
  1348. return UI_COLD;
  1349. } else if (uiIsHot(item)) {
  1350. return UI_HOT;
  1351. }
  1352. return UI_COLD;
  1353. }
  1354. #endif // OUI_IMPLEMENTATION