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.

1320 lines
39KB

  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. /*
  23. Revision 2 (2014-07-13)
  24. OUI (short for "Open UI", spoken like the french "oui" for "yes") is a
  25. platform agnostic single-header C library for layouting GUI elements and
  26. handling related user input. Together with a set of widget drawing and logic
  27. routines it can be used to build complex user interfaces.
  28. OUI is a semi-immediate GUI. Widget declarations are persistent for the duration
  29. of the setup and evaluation, but do not need to be kept around longer than one
  30. frame.
  31. OUI has no widget types; instead, it provides only one kind of element, "Items",
  32. which can be taylored to the application by the user and expanded with custom
  33. buffers and event handlers to behave as containers, buttons, sliders, radio
  34. buttons, and so on.
  35. OUI also does not draw anything; Instead it provides a set of functions to
  36. iterate and query the layouted items in order to allow client code to render
  37. each widget with its current state using a preferred graphics library.
  38. A basic setup for OUI usage looks like this:
  39. void app_main(...) {
  40. UIcontext *context = uiCreateContext();
  41. uiMakeCurrent(context);
  42. while (app_running()) {
  43. // update position of mouse cursor; the ui can also be updated
  44. // from received events.
  45. uiSetCursor(app_get_mouse_x(), app_get_mouse_y());
  46. // update button state
  47. for (int i = 0; i < 3; ++i)
  48. uiSetButton(i, app_get_button_state(i));
  49. // begin new UI declarations
  50. uiClear();
  51. // - UI setup code goes here -
  52. app_setup_ui();
  53. // layout UI
  54. uiLayout();
  55. // draw UI
  56. app_draw_ui(render_context,0,0,0);
  57. // update states and fire handlers
  58. uiProcess();
  59. }
  60. uiDestroyContext(context);
  61. }
  62. Here's an example setup for a checkbox control:
  63. typedef struct CheckBoxData {
  64. int type;
  65. const char *label;
  66. bool *checked;
  67. } CheckBoxData;
  68. // called when the item is clicked (see checkbox())
  69. void app_checkbox_handler(int item, UIevent event) {
  70. // retrieve custom data (see checkbox())
  71. const CheckBoxData *data = (const CheckBoxData *)uiGetData(item);
  72. // toggle value
  73. *data->checked = !(*data->checked);
  74. }
  75. // creates a checkbox control for a pointer to a boolean and attaches it to
  76. // a parent item.
  77. int checkbox(int parent, UIhandle handle, const char *label, bool *checked) {
  78. // create new ui item
  79. int item = uiItem();
  80. // set persistent handle for item that is used
  81. // to track activity over time
  82. uiSetHandle(item, handle);
  83. // set size of wiget; horizontal size is dynamic, vertical is fixed
  84. uiSetSize(item, 0, APP_WIDGET_HEIGHT);
  85. // attach checkbox handler, set to fire as soon as the left button is
  86. // pressed; UI_BUTTON0_HOT_UP is also a popular alternative.
  87. uiSetHandler(item, app_checkbox_handler, UI_BUTTON0_DOWN);
  88. // store some custom data with the checkbox that we use for rendering
  89. // and value changes.
  90. CheckBoxData *data = (CheckBoxData *)uiAllocData(item, sizeof(CheckBoxData));
  91. // assign a custom typeid to the data so the renderer knows how to
  92. // render this control.
  93. data->type = APP_WIDGET_CHECKBOX;
  94. data->label = label;
  95. data->checked = checked;
  96. // append to parent
  97. uiAppend(parent, item);
  98. return item;
  99. }
  100. A simple recursive drawing routine can look like this:
  101. void app_draw_ui(AppRenderContext *ctx, int item, int x, int y) {
  102. // retrieve custom data and cast it to an int; we assume the first member
  103. // of every widget data item to be an "int type" field.
  104. const int *type = (const int *)uiGetData(item);
  105. // get the widgets relative rectangle and offset by the parents
  106. // absolute position.
  107. UIrect rect = uiGetRect(item);
  108. rect.x += x;
  109. rect.y += y;
  110. // if a type is set, this is a specialized widget
  111. if (type) {
  112. switch(*type) {
  113. default: break;
  114. case APP_WIDGET_LABEL: {
  115. // ...
  116. } break;
  117. case APP_WIDGET_BUTTON: {
  118. // ...
  119. } break;
  120. case APP_WIDGET_CHECKBOX: {
  121. // cast to the full data type
  122. const CheckBoxData *data = (CheckBoxData*)type;
  123. // get the widgets current state
  124. int state = uiGetState(item);
  125. // if the value is set, the state is always active
  126. if (*data->checked)
  127. state = UI_ACTIVE;
  128. // draw the checkbox
  129. app_draw_checkbox(ctx, rect, state, data->label);
  130. } break;
  131. }
  132. }
  133. // iterate through all children and draw
  134. int kid = uiFirstChild(item);
  135. while (kid >= 0) {
  136. app_draw_ui(ctx, kid, rect.x, rect.y);
  137. kid = uiNextSibling(kid);
  138. }
  139. }
  140. See example.cpp in the repository for a full usage example.
  141. */
  142. // limits
  143. // maximum number of items that may be added (must be power of 2)
  144. #define UI_MAX_ITEMS 4096
  145. // maximum size in bytes reserved for storage of application dependent data
  146. // as passed to uiAllocData().
  147. #define UI_MAX_BUFFERSIZE 1048576
  148. // maximum size in bytes of a single data buffer passed to uiAllocData().
  149. #define UI_MAX_DATASIZE 4096
  150. // maximum depth of nested containers
  151. #define UI_MAX_DEPTH 64
  152. typedef unsigned int UIuint;
  153. // opaque UI context
  154. typedef struct UIcontext UIcontext;
  155. // application defined context handle
  156. typedef unsigned long long UIhandle;
  157. // item states as returned by uiGetState()
  158. typedef enum UIitemState {
  159. // the item is inactive
  160. UI_COLD = 0,
  161. // the item is inactive, but the cursor is hovering over this item
  162. UI_HOT = 1,
  163. // the item is toggled or activated (depends on item kind)
  164. UI_ACTIVE = 2,
  165. // the item is unresponsive
  166. UI_FROZEN = 3
  167. } UIitemState;
  168. // layout flags
  169. typedef enum UIlayoutFlags {
  170. // anchor to left item or left side of parent
  171. UI_LEFT = 1,
  172. // anchor to top item or top side of parent
  173. UI_TOP = 2,
  174. // anchor to right item or right side of parent
  175. UI_RIGHT = 4,
  176. // anchor to bottom item or bottom side of parent
  177. UI_DOWN = 8,
  178. // anchor to both left and right item or parent borders
  179. UI_HFILL = 5,
  180. // anchor to both top and bottom item or parent borders
  181. UI_VFILL = 10,
  182. // center horizontally, with left margin as offset
  183. UI_HCENTER = 0,
  184. // center vertically, with top margin as offset
  185. UI_VCENTER = 0,
  186. // center in both directions, with left/top margin as offset
  187. UI_CENTER = 0,
  188. // anchor to all four directions
  189. UI_FILL = 15,
  190. } UIlayoutFlags;
  191. // event flags
  192. typedef enum UIevent {
  193. // on button 0 down
  194. UI_BUTTON0_DOWN = 0x01,
  195. // on button 0 up
  196. // when this event has a handler, uiGetState() will return UI_ACTIVE as
  197. // long as button 0 is down.
  198. UI_BUTTON0_UP = 0x02,
  199. // on button 0 up while item is hovered
  200. // when this event has a handler, uiGetState() will return UI_ACTIVE
  201. // when the cursor is hovering the items rectangle; this is the
  202. // behavior expected for buttons.
  203. UI_BUTTON0_HOT_UP = 0x04,
  204. // item is being captured (button 0 constantly pressed);
  205. // when this event has a handler, uiGetState() will return UI_ACTIVE as
  206. // long as button 0 is down.
  207. UI_BUTTON0_CAPTURE = 0x08,
  208. // item has received a new child
  209. // this can be used to allow container items to configure child items
  210. // as they appear.
  211. UI_APPEND = 0x10,
  212. } UIevent;
  213. // handler callback; event is one of UI_EVENT_*
  214. typedef void (*UIhandler)(int item, UIevent event);
  215. // for cursor positions, mainly
  216. typedef struct UIvec2 {
  217. union {
  218. int v[2];
  219. struct { int x, y; };
  220. };
  221. } UIvec2;
  222. // layout rectangle
  223. typedef struct UIrect {
  224. union {
  225. int v[4];
  226. struct { int x, y, w, h; };
  227. };
  228. } UIrect;
  229. // unless declared otherwise, all operations have the complexity O(1).
  230. // Context Management
  231. // ------------------
  232. // create a new UI context; call uiMakeCurrent() to make this context the
  233. // current context. The context is managed by the client and must be released
  234. // using uiDestroyContext()
  235. UIcontext *uiCreateContext();
  236. // select an UI context as the current context; a context must always be
  237. // selected before using any of the other UI functions
  238. void uiMakeCurrent(UIcontext *ctx);
  239. // release the memory of an UI context created with uiCreateContext(); if the
  240. // context is the current context, the current context will be set to NULL
  241. void uiDestroyContext(UIcontext *ctx);
  242. // Input Control
  243. // -------------
  244. // sets the current cursor position (usually belonging to a mouse) to the
  245. // screen coordinates at (x,y)
  246. void uiSetCursor(int x, int y);
  247. // returns the current cursor position in screen coordinates as set by
  248. // uiSetCursor()
  249. UIvec2 uiGetCursor();
  250. // returns the offset of the cursor relative to the last call to uiProcess()
  251. UIvec2 uiGetCursorDelta();
  252. // returns the beginning point of a drag operation.
  253. UIvec2 uiGetCursorStart();
  254. // returns the offset of the cursor relative to the beginning point of a drag
  255. // operation.
  256. UIvec2 uiGetCursorStartDelta();
  257. // sets a mouse or gamepad button as pressed/released
  258. // button is in the range 0..63 and maps to an application defined input
  259. // source.
  260. // enabled is 1 for pressed, 0 for released
  261. void uiSetButton(int button, int enabled);
  262. // returns the current state of an application dependent input button
  263. // as set by uiSetButton().
  264. // the function returns 1 if the button has been set to pressed, 0 for released.
  265. int uiGetButton(int button);
  266. // Stages
  267. // ------
  268. // clear the item buffer; uiClear() should be called before the first
  269. // UI declaration for this frame to avoid concatenation of the same UI multiple
  270. // times.
  271. // After the call, all previously declared item IDs are invalid, and all
  272. // application dependent context data has been freed.
  273. void uiClear();
  274. // layout all added items starting from the root item 0.
  275. // after calling uiLayout(), no further modifications to the item tree should
  276. // be done until the next call to uiClear().
  277. // It is safe to immediately draw the items after a call to uiLayout().
  278. // this is an O(N) operation for N = number of declared items.
  279. void uiLayout();
  280. // update the internal state according to the current cursor position and
  281. // button states, and call all registered handlers.
  282. // after calling uiProcess(), no further modifications to the item tree should
  283. // be done until the next call to uiClear().
  284. // Items should be drawn before a call to uiProcess()
  285. // this is an O(N) operation for N = number of declared items.
  286. void uiProcess();
  287. // UI Declaration
  288. // --------------
  289. // create a new UI item and return the new items ID.
  290. int uiItem();
  291. // set an items state to frozen; the UI will not recurse into frozen items
  292. // when searching for hot or active items; subsequently, frozen items and
  293. // their child items will not cause mouse event notifications.
  294. // The frozen state is not applied recursively; uiGetState() will report
  295. // UI_COLD for child items. Upon encountering a frozen item, the drawing
  296. // routine needs to handle rendering of child items appropriately.
  297. // see example.cpp for a demonstration.
  298. void uiSetFrozen(int item, int enable);
  299. // set the application-dependent handle of an item.
  300. // handle is an application defined 64-bit handle. If handle is 0, the item
  301. // will not be interactive.
  302. void uiSetHandle(int item, UIhandle handle);
  303. // allocate space for application-dependent context data and return the pointer
  304. // if successful. If no data has been allocated, a new pointer is returned.
  305. // Otherwise, an assertion is thrown.
  306. // The memory of the pointer is managed by the UI context.
  307. void *uiAllocData(int item, int size);
  308. // set the handler callback for an interactive item.
  309. // flags is a combination of UI_EVENT_* and designates for which events the
  310. // handler should be called.
  311. void uiSetHandler(int item, UIhandler handler, int flags);
  312. // assign an item to a container.
  313. // an item ID of 0 refers to the root item.
  314. // if child is already assigned to a parent, an assertion will be thrown.
  315. // the function returns the child item ID
  316. int uiAppend(int item, int child);
  317. // set the size of the item; a size of 0 indicates the dimension to be
  318. // dynamic; if the size is set, the item can not expand beyond that size.
  319. void uiSetSize(int item, int w, int h);
  320. // set the anchoring behavior of the item to one or multiple UIlayoutFlags
  321. void uiSetLayout(int item, int flags);
  322. // set the left, top, right and bottom margins of an item; when the item is
  323. // anchored to the parent or another item, the margin controls the distance
  324. // from the neighboring element.
  325. void uiSetMargins(int item, int l, int t, int r, int b);
  326. // anchor the item to another sibling within the same container, so that the
  327. // sibling is left to this item.
  328. void uiSetRelToLeft(int item, int other);
  329. // anchor the item to another sibling within the same container, so that the
  330. // sibling is above this item.
  331. void uiSetRelToTop(int item, int other);
  332. // anchor the item to another sibling within the same container, so that the
  333. // sibling is right to this item.
  334. void uiSetRelToRight(int item, int other);
  335. // anchor the item to another sibling within the same container, so that the
  336. // sibling is below this item.
  337. void uiSetRelToDown(int item, int other);
  338. // Iteration
  339. // ---------
  340. // returns the first child item of a container item. If the item is not
  341. // a container or does not contain any items, -1 is returned.
  342. // if item is 0, the first child item of the root item will be returned.
  343. int uiFirstChild(int item);
  344. // returns the last child item of a container item. If the item is not
  345. // a container or does not contain any items, -1 is returned.
  346. // if item is 0, the last child item of the root item will be returned.
  347. int uiLastChild(int item);
  348. // returns an items parent container item.
  349. // if item is 0, -1 will be returned.
  350. int uiParent(int item);
  351. // returns an items next sibling in the list of the parent containers children.
  352. // if item is 0 or the item is the last child item, -1 will be returned.
  353. int uiNextSibling(int item);
  354. // returns an items previous sibling in the list of the parent containers
  355. // children.
  356. // if item is 0 or the item is the first child item, -1 will be returned.
  357. int uiPrevSibling(int item);
  358. // Querying
  359. // --------
  360. // return the current state of the item. This state is only valid after
  361. // a call to uiProcess().
  362. // The returned value is one of UI_COLD, UI_HOT, UI_ACTIVE, UI_FROZEN.
  363. UIitemState uiGetState(int item);
  364. // return the application-dependent handle of the item as passed to uiSetHandle().
  365. UIhandle uiGetHandle(int item);
  366. // return the item with the given application-dependent handle as assigned by
  367. // uiSetHandle() or -1 if unsuccessful.
  368. int uiGetItem(UIhandle handle);
  369. // return the item that is currently under the cursor
  370. int uiGetHotItem();
  371. // return the application-dependent context data for an item as passed to
  372. // uiAllocData(). The memory of the pointer is managed by the UI context
  373. // and should not be altered.
  374. const void *uiGetData(int item);
  375. // return the handler callback for an item as passed to uiSetHandler()
  376. UIhandler uiGetHandler(int item);
  377. // return the handler flags for an item as passed to uiSetHandler()
  378. int uiGetHandlerFlags(int item);
  379. // returns the number of child items a container item contains. If the item
  380. // is not a container or does not contain any items, 0 is returned.
  381. // if item is 0, the child item count of the root item will be returned.
  382. int uiGetChildCount(int item);
  383. // returns an items child index relative to its parent. If the item is the
  384. // first item, the return value is 0; If the item is the last item, the return
  385. // value is equivalent to uiGetChildCount(uiParent(item))-1.
  386. // if item is 0, 0 will be returned.
  387. int uiGetChildId(int item);
  388. // returns the items layout rectangle relative to the parent. If uiGetRect()
  389. // is called before uiProcess(), the values of the returned rectangle are
  390. // undefined.
  391. UIrect uiGetRect(int item);
  392. // when called from an input event handler, returns the active items absolute
  393. // layout rectangle. If uiGetActiveRect() is called outside of a handler,
  394. // the values of the returned rectangle are undefined.
  395. UIrect uiGetActiveRect();
  396. // return the width of the item as set by uiSetSize()
  397. int uiGetWidth(int item);
  398. // return the height of the item as set by uiSetSize()
  399. int uiGetHeight(int item);
  400. // return the anchoring behavior as set by uiSetLayout()
  401. int uiGetLayout(int item);
  402. // return the left margin of the item as set with uiSetMargins()
  403. int uiGetMarginLeft(int item);
  404. // return the top margin of the item as set with uiSetMargins()
  405. int uiGetMarginTop(int item);
  406. // return the right margin of the item as set with uiSetMargins()
  407. int uiGetMarginRight(int item);
  408. // return the bottom margin of the item as set with uiSetMargins()
  409. int uiGetMarginDown(int item);
  410. // return the items anchored sibling as assigned with uiSetRelToLeft()
  411. // or -1 if not set.
  412. int uiGetRelToLeft(int item);
  413. // return the items anchored sibling as assigned with uiSetRelToTop()
  414. // or -1 if not set.
  415. int uiGetRelToTop(int item);
  416. // return the items anchored sibling as assigned with uiSetRelToRight()
  417. // or -1 if not set.
  418. int uiGetRelToRight(int item);
  419. // return the items anchored sibling as assigned with uiSetRelToBottom()
  420. // or -1 if not set.
  421. int uiGetRelToDown(int item);
  422. #endif // _OUI_H_
  423. #ifdef OUI_IMPLEMENTATION
  424. #include <assert.h>
  425. #ifdef _MSC_VER
  426. #pragma warning (disable: 4996) // Switch off security warnings
  427. #pragma warning (disable: 4100) // Switch off unreferenced formal parameter warnings
  428. #ifdef __cplusplus
  429. #define UI_INLINE inline
  430. #else
  431. #define UI_INLINE
  432. #endif
  433. #else
  434. #define UI_INLINE inline
  435. #endif
  436. #define UI_MAX_KIND 16
  437. typedef struct UIitem {
  438. // declaration independent unique handle (for persistence)
  439. UIhandle handle;
  440. // handler
  441. UIhandler handler;
  442. // container structure
  443. // number of kids
  444. int numkids;
  445. // index of first kid
  446. int firstkid;
  447. // index of last kid
  448. int lastkid;
  449. // child structure
  450. // parent item
  451. int parent;
  452. // index of kid relative to parent
  453. int kidid;
  454. // index of next sibling with same parent
  455. int nextitem;
  456. // index of previous sibling with same parent
  457. int previtem;
  458. // one or multiple of UIlayoutFlags
  459. int layout_flags;
  460. // size
  461. UIvec2 size;
  462. // visited flags for layouting
  463. int visited;
  464. // margin offsets, interpretation depends on flags
  465. int margins[4];
  466. // neighbors to position borders to
  467. int relto[4];
  468. // computed size
  469. UIvec2 computed_size;
  470. // relative rect
  471. UIrect rect;
  472. // attributes
  473. int frozen;
  474. // index of data or -1 for none
  475. int data;
  476. // size of data
  477. int datasize;
  478. // a combination of UIevents
  479. int event_flags;
  480. } UIitem;
  481. typedef enum UIstate {
  482. UI_STATE_IDLE = 0,
  483. UI_STATE_CAPTURE,
  484. } UIstate;
  485. typedef struct UIhandle_entry {
  486. unsigned int key;
  487. int item;
  488. } UIhandle_entry;
  489. struct UIcontext {
  490. // button state in this frame
  491. unsigned long long buttons;
  492. // button state in the previous frame
  493. unsigned long long last_buttons;
  494. // where the cursor was at the beginning of the active state
  495. UIvec2 start_cursor;
  496. // where the cursor was last frame
  497. UIvec2 last_cursor;
  498. // where the cursor is currently
  499. UIvec2 cursor;
  500. UIhandle hot_handle;
  501. UIhandle active_handle;
  502. UIrect hot_rect;
  503. UIrect active_rect;
  504. UIstate state;
  505. int hot_item;
  506. int count;
  507. UIitem items[UI_MAX_ITEMS];
  508. int datasize;
  509. unsigned char data[UI_MAX_BUFFERSIZE];
  510. UIhandle_entry handles[UI_MAX_ITEMS];
  511. };
  512. UI_INLINE int ui_max(int a, int b) {
  513. return (a>b)?a:b;
  514. }
  515. UI_INLINE int ui_min(int a, int b) {
  516. return (a<b)?a:b;
  517. }
  518. static UIcontext *ui_context = NULL;
  519. UIcontext *uiCreateContext() {
  520. UIcontext *ctx = (UIcontext *)malloc(sizeof(UIcontext));
  521. memset(ctx, 0, sizeof(UIcontext));
  522. return ctx;
  523. }
  524. void uiMakeCurrent(UIcontext *ctx) {
  525. ui_context = ctx;
  526. if (ui_context)
  527. uiClear();
  528. }
  529. void uiDestroyContext(UIcontext *ctx) {
  530. if (ui_context == ctx)
  531. uiMakeCurrent(NULL);
  532. free(ctx);
  533. }
  534. UI_INLINE unsigned int uiHashHandle(UIhandle handle) {
  535. handle = (handle+(handle>>32)) & 0xffffffff;
  536. unsigned int x = (unsigned int)handle;
  537. x += (x>>6)+(x>>19);
  538. x += x<<16;
  539. x ^= x<<3;
  540. x += x>>5;
  541. x ^= x<<2;
  542. x += x>>15;
  543. x ^= x<<10;
  544. return x?x:1; // must not be zero
  545. }
  546. UI_INLINE unsigned int uiHashProbeDistance(unsigned int key, unsigned int slot_index) {
  547. unsigned int pos = key & (UI_MAX_ITEMS-1);
  548. return (slot_index + UI_MAX_ITEMS - pos) & (UI_MAX_ITEMS-1);
  549. }
  550. UI_INLINE UIhandle_entry *uiHashLookupHandle(unsigned int key) {
  551. assert(ui_context);
  552. int pos = key & (UI_MAX_ITEMS-1);
  553. unsigned int dist = 0;
  554. for (;;) {
  555. UIhandle_entry *entry = ui_context->handles + pos;
  556. unsigned int pos_key = entry->key;
  557. if (!pos_key) return NULL;
  558. else if (entry->key == key)
  559. return entry;
  560. else if (dist > uiHashProbeDistance(pos_key, pos))
  561. return NULL;
  562. pos = (pos+1) & (UI_MAX_ITEMS-1);
  563. ++dist;
  564. }
  565. }
  566. int uiGetItem(UIhandle handle) {
  567. unsigned int key = uiHashHandle(handle);
  568. UIhandle_entry *e = uiHashLookupHandle(key);
  569. return e?(e->item):-1;
  570. }
  571. static void uiHashInsertHandle(UIhandle handle, int item) {
  572. unsigned int key = uiHashHandle(handle);
  573. UIhandle_entry *e = uiHashLookupHandle(key);
  574. if (e) { // update
  575. e->item = item;
  576. return;
  577. }
  578. int pos = key & (UI_MAX_ITEMS-1);
  579. unsigned int dist = 0;
  580. for (unsigned int i = 0; i < UI_MAX_ITEMS; ++i) {
  581. int index = (pos + i) & (UI_MAX_ITEMS-1);
  582. unsigned int pos_key = ui_context->handles[index].key;
  583. if (!pos_key) {
  584. ui_context->handles[index].key = key;
  585. ui_context->handles[index].item = item;
  586. break;
  587. } else {
  588. unsigned int probe_distance = uiHashProbeDistance(pos_key, index);
  589. if (dist > probe_distance) {
  590. unsigned int oldkey = ui_context->handles[index].key;
  591. unsigned int olditem = ui_context->handles[index].item;
  592. ui_context->handles[index].key = key;
  593. ui_context->handles[index].item = item;
  594. key = oldkey;
  595. item = olditem;
  596. dist = probe_distance;
  597. }
  598. }
  599. ++dist;
  600. }
  601. }
  602. void uiSetButton(int button, int enabled) {
  603. assert(ui_context);
  604. unsigned long long mask = 1ull<<button;
  605. // set new bit
  606. ui_context->buttons = (enabled)?
  607. (ui_context->buttons | mask):
  608. (ui_context->buttons & ~mask);
  609. }
  610. int uiGetLastButton(int button) {
  611. assert(ui_context);
  612. return (ui_context->last_buttons & (1ull<<button))?1:0;
  613. }
  614. int uiGetButton(int button) {
  615. assert(ui_context);
  616. return (ui_context->buttons & (1ull<<button))?1:0;
  617. }
  618. int uiButtonPressed(int button) {
  619. assert(ui_context);
  620. return !uiGetLastButton(button) && uiGetButton(button);
  621. }
  622. int uiButtonReleased(int button) {
  623. assert(ui_context);
  624. return uiGetLastButton(button) && !uiGetButton(button);
  625. }
  626. void uiSetCursor(int x, int y) {
  627. assert(ui_context);
  628. ui_context->cursor.x = x;
  629. ui_context->cursor.y = y;
  630. }
  631. UIvec2 uiGetCursor() {
  632. assert(ui_context);
  633. return ui_context->cursor;
  634. }
  635. UIvec2 uiGetCursorStart() {
  636. assert(ui_context);
  637. return ui_context->start_cursor;
  638. }
  639. UIvec2 uiGetCursorDelta() {
  640. assert(ui_context);
  641. UIvec2 result = {{{
  642. ui_context->cursor.x - ui_context->last_cursor.x,
  643. ui_context->cursor.y - ui_context->last_cursor.y
  644. }}};
  645. return result;
  646. }
  647. UIvec2 uiGetCursorStartDelta() {
  648. assert(ui_context);
  649. UIvec2 result = {{{
  650. ui_context->cursor.x - ui_context->start_cursor.x,
  651. ui_context->cursor.y - ui_context->start_cursor.y
  652. }}};
  653. return result;
  654. }
  655. UIitem *uiItemPtr(int item) {
  656. assert(ui_context && (item >= 0) && (item < ui_context->count));
  657. return ui_context->items + item;
  658. }
  659. int uiGetHotItem() {
  660. assert(ui_context);
  661. return ui_context->hot_item;
  662. }
  663. void uiClear() {
  664. assert(ui_context);
  665. ui_context->count = 0;
  666. ui_context->datasize = 0;
  667. ui_context->hot_item = -1;
  668. memset(ui_context->handles, 0, sizeof(ui_context->handles));
  669. }
  670. int uiItem() {
  671. assert(ui_context);
  672. assert(ui_context->count < UI_MAX_ITEMS);
  673. int idx = ui_context->count++;
  674. UIitem *item = uiItemPtr(idx);
  675. memset(item, 0, sizeof(UIitem));
  676. item->parent = -1;
  677. item->firstkid = -1;
  678. item->lastkid = -1;
  679. item->nextitem = -1;
  680. item->previtem = -1;
  681. item->data = -1;
  682. for (int i = 0; i < 4; ++i)
  683. item->relto[i] = -1;
  684. return idx;
  685. }
  686. void uiNotifyItem(int item, UIevent event) {
  687. UIitem *pitem = uiItemPtr(item);
  688. if (pitem->handler && (pitem->event_flags & event)) {
  689. pitem->handler(item, event);
  690. }
  691. }
  692. int uiAppend(int item, int child) {
  693. assert(child > 0);
  694. assert(uiParent(child) == -1);
  695. UIitem *pitem = uiItemPtr(child);
  696. UIitem *pparent = uiItemPtr(item);
  697. pitem->parent = item;
  698. pitem->kidid = pparent->numkids++;
  699. if (pparent->lastkid < 0) {
  700. pparent->firstkid = child;
  701. pparent->lastkid = child;
  702. } else {
  703. pitem->previtem = pparent->lastkid;
  704. uiItemPtr(pparent->lastkid)->nextitem = child;
  705. pparent->lastkid = child;
  706. }
  707. uiNotifyItem(item, UI_APPEND);
  708. return child;
  709. }
  710. void uiSetFrozen(int item, int enable) {
  711. UIitem *pitem = uiItemPtr(item);
  712. pitem->frozen = enable;
  713. }
  714. void uiSetSize(int item, int w, int h) {
  715. UIitem *pitem = uiItemPtr(item);
  716. pitem->size.x = w;
  717. pitem->size.y = h;
  718. }
  719. int uiGetWidth(int item) {
  720. return uiItemPtr(item)->size.x;
  721. }
  722. int uiGetHeight(int item) {
  723. return uiItemPtr(item)->size.y;
  724. }
  725. void uiSetLayout(int item, int flags) {
  726. uiItemPtr(item)->layout_flags = flags;
  727. }
  728. int uiGetLayout(int item) {
  729. return uiItemPtr(item)->layout_flags;
  730. }
  731. void uiSetMargins(int item, int l, int t, int r, int b) {
  732. UIitem *pitem = uiItemPtr(item);
  733. pitem->margins[0] = l;
  734. pitem->margins[1] = t;
  735. pitem->margins[2] = r;
  736. pitem->margins[3] = b;
  737. }
  738. int uiGetMarginLeft(int item) {
  739. return uiItemPtr(item)->margins[0];
  740. }
  741. int uiGetMarginTop(int item) {
  742. return uiItemPtr(item)->margins[1];
  743. }
  744. int uiGetMarginRight(int item) {
  745. return uiItemPtr(item)->margins[2];
  746. }
  747. int uiGetMarginDown(int item) {
  748. return uiItemPtr(item)->margins[3];
  749. }
  750. void uiSetRelToLeft(int item, int other) {
  751. assert((other < 0) || (uiParent(other) == uiParent(item)));
  752. uiItemPtr(item)->relto[0] = other;
  753. }
  754. int uiGetRelToLeft(int item) {
  755. return uiItemPtr(item)->relto[0];
  756. }
  757. void uiSetRelToTop(int item, int other) {
  758. assert((other < 0) || (uiParent(other) == uiParent(item)));
  759. uiItemPtr(item)->relto[1] = other;
  760. }
  761. int uiGetRelToTop(int item) {
  762. return uiItemPtr(item)->relto[1];
  763. }
  764. void uiSetRelToRight(int item, int other) {
  765. assert((other < 0) || (uiParent(other) == uiParent(item)));
  766. uiItemPtr(item)->relto[2] = other;
  767. }
  768. int uiGetRelToRight(int item) {
  769. return uiItemPtr(item)->relto[2];
  770. }
  771. void uiSetRelToDown(int item, int other) {
  772. assert((other < 0) || (uiParent(other) == uiParent(item)));
  773. uiItemPtr(item)->relto[3] = other;
  774. }
  775. int uiGetRelToDown(int item) {
  776. return uiItemPtr(item)->relto[3];
  777. }
  778. UI_INLINE void uiComputeChainSize(UIitem *pkid,
  779. int *need_size, int *hard_size, int dim) {
  780. UIitem *pitem = pkid;
  781. int wdim = dim+2;
  782. int size = pitem->rect.v[wdim] + pitem->margins[dim] + pitem->margins[wdim];
  783. *need_size = size;
  784. *hard_size = pitem->size.v[dim]?size:0;
  785. int it = 0;
  786. pitem->visited |= 1<<dim;
  787. // traverse along left neighbors
  788. while ((pitem->layout_flags>>dim) & UI_LEFT) {
  789. if (pitem->relto[dim] < 0) break;
  790. pitem = uiItemPtr(pitem->relto[dim]);
  791. pitem->visited |= 1<<dim;
  792. size = pitem->rect.v[wdim] + pitem->margins[dim] + pitem->margins[wdim];
  793. *need_size = (*need_size) + size;
  794. *hard_size = (*hard_size) + (pitem->size.v[dim]?size:0);
  795. it++;
  796. assert(it<1000000); // infinite loop
  797. }
  798. // traverse along right neighbors
  799. pitem = pkid;
  800. it = 0;
  801. while ((pitem->layout_flags>>dim) & UI_RIGHT) {
  802. if (pitem->relto[wdim] < 0) break;
  803. pitem = uiItemPtr(pitem->relto[wdim]);
  804. pitem->visited |= 1<<dim;
  805. size = pitem->rect.v[wdim] + pitem->margins[dim] + pitem->margins[wdim];
  806. *need_size = (*need_size) + size;
  807. *hard_size = (*hard_size) + (pitem->size.v[dim]?size:0);
  808. it++;
  809. assert(it<1000000); // infinite loop
  810. }
  811. }
  812. UI_INLINE void uiComputeSizeDim(UIitem *pitem, int dim) {
  813. int wdim = dim+2;
  814. int need_size = 0;
  815. int hard_size = 0;
  816. int kid = pitem->firstkid;
  817. while (kid >= 0) {
  818. UIitem *pkid = uiItemPtr(kid);
  819. if (!(pkid->visited & (1<<dim))) {
  820. int ns,hs;
  821. uiComputeChainSize(pkid, &ns, &hs, dim);
  822. need_size = ui_max(need_size, ns);
  823. hard_size = ui_max(hard_size, hs);
  824. }
  825. kid = uiNextSibling(kid);
  826. }
  827. pitem->computed_size.v[dim] = hard_size;
  828. if (pitem->size.v[dim]) {
  829. pitem->rect.v[wdim] = pitem->size.v[dim];
  830. } else {
  831. pitem->rect.v[wdim] = need_size;
  832. }
  833. }
  834. static void uiComputeBestSize(int item, int dim) {
  835. UIitem *pitem = uiItemPtr(item);
  836. pitem->visited = 0;
  837. // children expand the size
  838. int kid = uiFirstChild(item);
  839. while (kid >= 0) {
  840. uiComputeBestSize(kid, dim);
  841. kid = uiNextSibling(kid);
  842. }
  843. uiComputeSizeDim(pitem, dim);
  844. }
  845. static void uiLayoutChildItem(UIitem *pparent, UIitem *pitem,
  846. int *dyncount, int *consumed_space, int dim) {
  847. if (pitem->visited & (4<<dim)) return;
  848. pitem->visited |= (4<<dim);
  849. int wdim = dim+2;
  850. int x = 0;
  851. int s = pparent->rect.v[wdim];
  852. int flags = pitem->layout_flags>>dim;
  853. int hasl = (flags & UI_LEFT) && (pitem->relto[dim] >= 0);
  854. int hasr = (flags & UI_RIGHT) && (pitem->relto[wdim] >= 0);
  855. if ((flags & UI_HFILL) != UI_HFILL) {
  856. *consumed_space = (*consumed_space)
  857. + pitem->rect.v[wdim]
  858. + pitem->margins[wdim]
  859. + pitem->margins[dim];
  860. } else if (!pitem->size.v[dim]) {
  861. *dyncount = (*dyncount)+1;
  862. }
  863. if (hasl) {
  864. UIitem *pl = uiItemPtr(pitem->relto[dim]);
  865. uiLayoutChildItem(pparent, pl, dyncount, consumed_space, dim);
  866. x = pl->rect.v[dim]+pl->rect.v[wdim]+pl->margins[wdim];
  867. s -= x;
  868. }
  869. if (hasr) {
  870. UIitem *pl = uiItemPtr(pitem->relto[wdim]);
  871. uiLayoutChildItem(pparent, pl, dyncount, consumed_space, dim);
  872. s = pl->rect.v[dim]-pl->margins[dim]-x;
  873. }
  874. switch(flags & UI_HFILL) {
  875. default:
  876. case UI_HCENTER: {
  877. pitem->rect.v[dim] = x+(s-pitem->rect.v[wdim])/2+pitem->margins[dim];
  878. } break;
  879. case UI_LEFT: {
  880. pitem->rect.v[dim] = x+pitem->margins[dim];
  881. } break;
  882. case UI_RIGHT: {
  883. pitem->rect.v[dim] = x+s-pitem->rect.v[wdim]-pitem->margins[wdim];
  884. } break;
  885. case UI_HFILL: {
  886. if (pitem->size.v[dim]) { // hard maximum size; can't stretch
  887. if (!hasl)
  888. pitem->rect.v[dim] = x+pitem->margins[dim];
  889. else
  890. pitem->rect.v[dim] = x+s-pitem->rect.v[wdim]-pitem->margins[wdim];
  891. } else {
  892. if (1) { //!pitem->rect.v[wdim]) {
  893. //int width = (pparent->rect.v[wdim] - pparent->computed_size.v[dim]);
  894. int width = (pparent->rect.v[wdim] - (*consumed_space));
  895. int space = width / (*dyncount);
  896. //int rest = width - space*(*dyncount);
  897. if (!hasl) {
  898. pitem->rect.v[dim] = x+pitem->margins[dim];
  899. pitem->rect.v[wdim] = s-pitem->margins[dim]-pitem->margins[wdim];
  900. } else {
  901. pitem->rect.v[wdim] = space-pitem->margins[dim]-pitem->margins[wdim];
  902. pitem->rect.v[dim] = x+s-pitem->rect.v[wdim]-pitem->margins[wdim];
  903. }
  904. } else {
  905. pitem->rect.v[dim] = x+pitem->margins[dim];
  906. pitem->rect.v[wdim] = s-pitem->margins[dim]-pitem->margins[wdim];
  907. }
  908. }
  909. } break;
  910. }
  911. }
  912. UI_INLINE void uiLayoutItemDim(UIitem *pitem, int dim) {
  913. int wdim = dim+2;
  914. int kid = pitem->firstkid;
  915. int consumed_space = 0;
  916. int dyncount = 0;
  917. while (kid >= 0) {
  918. UIitem *pkid = uiItemPtr(kid);
  919. uiLayoutChildItem(pitem, pkid, &dyncount, &consumed_space, dim);
  920. kid = uiNextSibling(kid);
  921. }
  922. }
  923. static void uiLayoutItem(int item, int dim) {
  924. UIitem *pitem = uiItemPtr(item);
  925. uiLayoutItemDim(pitem, dim);
  926. int kid = uiFirstChild(item);
  927. while (kid >= 0) {
  928. uiLayoutItem(kid, dim);
  929. kid = uiNextSibling(kid);
  930. }
  931. }
  932. UIrect uiGetRect(int item) {
  933. return uiItemPtr(item)->rect;
  934. }
  935. UIrect uiGetActiveRect() {
  936. assert(ui_context);
  937. return ui_context->active_rect;
  938. }
  939. int uiFirstChild(int item) {
  940. return uiItemPtr(item)->firstkid;
  941. }
  942. int uiLastChild(int item) {
  943. return uiItemPtr(item)->lastkid;
  944. }
  945. int uiNextSibling(int item) {
  946. return uiItemPtr(item)->nextitem;
  947. }
  948. int uiPrevSibling(int item) {
  949. return uiItemPtr(item)->previtem;
  950. }
  951. int uiParent(int item) {
  952. return uiItemPtr(item)->parent;
  953. }
  954. const void *uiGetData(int item) {
  955. UIitem *pitem = uiItemPtr(item);
  956. if (pitem->data < 0) return NULL;
  957. return ui_context->data + pitem->data;
  958. }
  959. void *uiAllocData(int item, int size) {
  960. assert((size > 0) && (size < UI_MAX_DATASIZE));
  961. UIitem *pitem = uiItemPtr(item);
  962. assert(pitem->data < 0);
  963. assert((ui_context->datasize+size) <= UI_MAX_BUFFERSIZE);
  964. pitem->data = ui_context->datasize;
  965. ui_context->datasize += size;
  966. return ui_context->data + pitem->data;
  967. }
  968. void uiSetHandle(int item, UIhandle handle) {
  969. uiItemPtr(item)->handle = handle;
  970. if (handle) {
  971. uiHashInsertHandle(handle, item);
  972. }
  973. }
  974. UIhandle uiGetHandle(int item) {
  975. return uiItemPtr(item)->handle;
  976. }
  977. void uiSetHandler(int item, UIhandler handler, int flags) {
  978. UIitem *pitem = uiItemPtr(item);
  979. pitem->handler = handler;
  980. pitem->event_flags = flags;
  981. }
  982. UIhandler uiGetHandler(int item) {
  983. return uiItemPtr(item)->handler;
  984. }
  985. int uiGetHandlerFlags(int item) {
  986. return uiItemPtr(item)->event_flags;
  987. }
  988. int uiGetChildId(int item) {
  989. return uiItemPtr(item)->kidid;
  990. }
  991. int uiGetChildCount(int item) {
  992. return uiItemPtr(item)->numkids;
  993. }
  994. int uiFindItem(int item, int x, int y, int ox, int oy) {
  995. UIitem *pitem = uiItemPtr(item);
  996. if (pitem->frozen) return -1;
  997. UIrect rect = pitem->rect;
  998. x -= rect.x;
  999. y -= rect.y;
  1000. ox += rect.x;
  1001. oy += rect.y;
  1002. if ((x>=0)
  1003. && (y>=0)
  1004. && (x<rect.w)
  1005. && (y<rect.h)) {
  1006. int kid = uiFirstChild(item);
  1007. while (kid >= 0) {
  1008. int best_hit = uiFindItem(kid,x,y,ox,oy);
  1009. if (best_hit >= 0) return best_hit;
  1010. kid = uiNextSibling(kid);
  1011. }
  1012. rect.x += ox;
  1013. rect.y += oy;
  1014. ui_context->hot_rect = rect;
  1015. return item;
  1016. }
  1017. return -1;
  1018. }
  1019. void uiLayout() {
  1020. assert(ui_context);
  1021. if (!ui_context->count) return;
  1022. // compute widths
  1023. uiComputeBestSize(0,0);
  1024. // position root element rect
  1025. uiItemPtr(0)->rect.x = uiItemPtr(0)->margins[0];
  1026. uiLayoutItem(0,0);
  1027. // compute heights
  1028. uiComputeBestSize(0,1);
  1029. // position root element rect
  1030. uiItemPtr(0)->rect.y = uiItemPtr(0)->margins[1];
  1031. uiLayoutItem(0,1);
  1032. // drawing routines may require this to be set already
  1033. int hot = uiFindItem(0,
  1034. ui_context->cursor.x, ui_context->cursor.y, 0, 0);
  1035. ui_context->hot_item = hot;
  1036. }
  1037. void uiProcess() {
  1038. assert(ui_context);
  1039. if (!ui_context->count) return;
  1040. int hot_item = uiGetItem(ui_context->hot_handle);
  1041. int active_item = uiGetItem(ui_context->active_handle);
  1042. int hot = ui_context->hot_item;
  1043. switch(ui_context->state) {
  1044. default:
  1045. case UI_STATE_IDLE: {
  1046. ui_context->start_cursor = ui_context->cursor;
  1047. if (uiGetButton(0)) {
  1048. hot_item = -1;
  1049. ui_context->active_rect = ui_context->hot_rect;
  1050. active_item = hot;
  1051. if (active_item >= 0) {
  1052. uiNotifyItem(active_item, UI_BUTTON0_DOWN);
  1053. }
  1054. ui_context->state = UI_STATE_CAPTURE;
  1055. } else {
  1056. hot_item = hot;
  1057. }
  1058. } break;
  1059. case UI_STATE_CAPTURE: {
  1060. if (!uiGetButton(0)) {
  1061. if (active_item >= 0) {
  1062. uiNotifyItem(active_item, UI_BUTTON0_UP);
  1063. if (active_item == hot) {
  1064. uiNotifyItem(active_item, UI_BUTTON0_HOT_UP);
  1065. }
  1066. }
  1067. active_item = -1;
  1068. ui_context->state = UI_STATE_IDLE;
  1069. } else {
  1070. if (active_item >= 0) {
  1071. uiNotifyItem(active_item, UI_BUTTON0_CAPTURE);
  1072. }
  1073. if (hot == active_item)
  1074. hot_item = hot;
  1075. else
  1076. hot_item = -1;
  1077. }
  1078. } break;
  1079. }
  1080. ui_context->last_cursor = ui_context->cursor;
  1081. ui_context->hot_handle = (hot_item>=0)?
  1082. uiGetHandle(hot_item):0;
  1083. ui_context->active_handle = (active_item>=0)?
  1084. uiGetHandle(active_item):0;
  1085. }
  1086. static int uiIsActive(int item) {
  1087. assert(ui_context);
  1088. return (ui_context->active_handle)&&(uiGetHandle(item) == ui_context->active_handle);
  1089. }
  1090. static int uiIsHot(int item) {
  1091. assert(ui_context);
  1092. return (ui_context->hot_handle)&&(uiGetHandle(item) == ui_context->hot_handle);
  1093. }
  1094. UIitemState uiGetState(int item) {
  1095. UIitem *pitem = uiItemPtr(item);
  1096. if (pitem->frozen) return UI_FROZEN;
  1097. if (uiIsActive(item)) {
  1098. if (pitem->event_flags & (UI_BUTTON0_CAPTURE|UI_BUTTON0_UP)) return UI_ACTIVE;
  1099. if ((pitem->event_flags & UI_BUTTON0_HOT_UP)
  1100. && uiIsHot(item)) return UI_ACTIVE;
  1101. return UI_COLD;
  1102. } else if (uiIsHot(item)) {
  1103. return UI_HOT;
  1104. }
  1105. return UI_COLD;
  1106. }
  1107. #endif // OUI_IMPLEMENTATION