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.

1855 lines
55KB

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