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.

1211 lines
36KB

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