UI: naming of cursor options
[blender.git] / source / blender / editors / interface / interface.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): Blender Foundation 2002-2008, full recode.
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/editors/interface/interface.c
27  *  \ingroup edinterface
28  */
29
30
31 #include <float.h>
32 #include <limits.h>
33 #include <math.h>
34 #include <string.h>
35 #include <ctype.h>
36 #include <stddef.h>  /* offsetof() */
37
38 #include "MEM_guardedalloc.h"
39
40 #include "DNA_object_types.h"
41 #include "DNA_scene_types.h"
42 #include "DNA_screen_types.h"
43 #include "DNA_userdef_types.h"
44 #include "DNA_workspace_types.h"
45
46 #include "BLI_math.h"
47 #include "BLI_listbase.h"
48 #include "BLI_string.h"
49 #include "BLI_string_utf8.h"
50 #include "BLI_rect.h"
51
52 #include "BLI_utildefines.h"
53
54 #include "BKE_animsys.h"
55 #include "BKE_context.h"
56 #include "BKE_idprop.h"
57 #include "BKE_main.h"
58 #include "BKE_scene.h"
59 #include "BKE_screen.h"
60 #include "BKE_unit.h"
61
62 #include "GPU_glew.h"
63 #include "GPU_matrix.h"
64
65 #include "BLF_api.h"
66 #include "BLT_translation.h"
67
68 #include "UI_interface.h"
69 #include "UI_interface_icons.h"
70
71 #include "IMB_imbuf.h"
72
73 #include "WM_api.h"
74 #include "WM_types.h"
75 #include "WM_message.h"
76
77 #include "RNA_access.h"
78
79 #include "BPY_extern.h"
80
81 #include "ED_screen.h"
82
83 #include "IMB_colormanagement.h"
84
85 #include "DEG_depsgraph_query.h"
86
87 #include "interface_intern.h"
88
89 /* prototypes. */
90 static void ui_but_to_pixelrect(struct rcti *rect, const struct ARegion *ar, struct uiBlock *block, struct uiBut *but);
91
92 /* avoid unneeded calls to ui_but_value_get */
93 #define UI_BUT_VALUE_UNSET DBL_MAX
94 #define UI_GET_BUT_VALUE_INIT(_but, _value) if (_value == DBL_MAX) {  (_value) = ui_but_value_get(_but); } (void)0
95
96 #define B_NOP -1
97
98 /**
99  * a full doc with API notes can be found in 'blender/doc/guides/interface_API.txt'
100  *
101  * `uiBlahBlah()`       external function.
102  * `ui_blah_blah()`     internal function.
103  */
104
105 static void ui_but_free(const bContext *C, uiBut *but);
106
107 bool ui_block_is_menu(const uiBlock *block)
108 {
109         return (((block->flag & UI_BLOCK_LOOP) != 0) &&
110                 /* non-menu popups use keep-open, so check this is off */
111                 ((block->flag & UI_BLOCK_KEEP_OPEN) == 0));
112 }
113
114 bool ui_block_is_pie_menu(const uiBlock *block)
115 {
116         return ((block->flag & UI_BLOCK_RADIAL) != 0);
117 }
118
119 static bool ui_but_is_unit_radians_ex(UnitSettings *unit, const int unit_type)
120 {
121         return (unit->system_rotation == USER_UNIT_ROT_RADIANS && unit_type == PROP_UNIT_ROTATION);
122 }
123
124 static bool ui_but_is_unit_radians(const uiBut *but)
125 {
126         UnitSettings *unit = but->block->unit;
127         const int unit_type = UI_but_unit_type_get(but);
128
129         return ui_but_is_unit_radians_ex(unit, unit_type);
130 }
131
132 /* ************* window matrix ************** */
133
134 void ui_block_to_window_fl(const ARegion *ar, uiBlock *block, float *x, float *y)
135 {
136         float gx, gy;
137         int sx, sy, getsizex, getsizey;
138
139         getsizex = BLI_rcti_size_x(&ar->winrct) + 1;
140         getsizey = BLI_rcti_size_y(&ar->winrct) + 1;
141         sx = ar->winrct.xmin;
142         sy = ar->winrct.ymin;
143
144         gx = *x;
145         gy = *y;
146
147         if (block->panel) {
148                 gx += block->panel->ofsx;
149                 gy += block->panel->ofsy;
150         }
151
152         *x = ((float)sx) + ((float)getsizex) * (0.5f + 0.5f * (gx * block->winmat[0][0] + gy * block->winmat[1][0] + block->winmat[3][0]));
153         *y = ((float)sy) + ((float)getsizey) * (0.5f + 0.5f * (gx * block->winmat[0][1] + gy * block->winmat[1][1] + block->winmat[3][1]));
154 }
155
156 void ui_block_to_window(const ARegion *ar, uiBlock *block, int *x, int *y)
157 {
158         float fx, fy;
159
160         fx = *x;
161         fy = *y;
162
163         ui_block_to_window_fl(ar, block, &fx, &fy);
164
165         *x = (int)(fx + 0.5f);
166         *y = (int)(fy + 0.5f);
167 }
168
169 void ui_block_to_window_rctf(const ARegion *ar, uiBlock *block, rctf *rct_dst, const rctf *rct_src)
170 {
171         *rct_dst = *rct_src;
172         ui_block_to_window_fl(ar, block, &rct_dst->xmin, &rct_dst->ymin);
173         ui_block_to_window_fl(ar, block, &rct_dst->xmax, &rct_dst->ymax);
174 }
175
176 void ui_window_to_block_fl(const ARegion *ar, uiBlock *block, float *x, float *y)   /* for mouse cursor */
177 {
178         float a, b, c, d, e, f, px, py;
179         int sx, sy, getsizex, getsizey;
180
181         getsizex = BLI_rcti_size_x(&ar->winrct) + 1;
182         getsizey = BLI_rcti_size_y(&ar->winrct) + 1;
183         sx = ar->winrct.xmin;
184         sy = ar->winrct.ymin;
185
186         a = 0.5f * ((float)getsizex) * block->winmat[0][0];
187         b = 0.5f * ((float)getsizex) * block->winmat[1][0];
188         c = 0.5f * ((float)getsizex) * (1.0f + block->winmat[3][0]);
189
190         d = 0.5f * ((float)getsizey) * block->winmat[0][1];
191         e = 0.5f * ((float)getsizey) * block->winmat[1][1];
192         f = 0.5f * ((float)getsizey) * (1.0f + block->winmat[3][1]);
193
194         px = *x - sx;
195         py = *y - sy;
196
197         *y =  (a * (py - f) + d * (c - px)) / (a * e - d * b);
198         *x = (px - b * (*y) - c) / a;
199
200         if (block->panel) {
201                 *x -= block->panel->ofsx;
202                 *y -= block->panel->ofsy;
203         }
204 }
205
206 void ui_window_to_block(const ARegion *ar, uiBlock *block, int *x, int *y)
207 {
208         float fx, fy;
209
210         fx = *x;
211         fy = *y;
212
213         ui_window_to_block_fl(ar, block, &fx, &fy);
214
215         *x = (int)(fx + 0.5f);
216         *y = (int)(fy + 0.5f);
217 }
218
219 void ui_window_to_region(const ARegion *ar, int *x, int *y)
220 {
221         *x -= ar->winrct.xmin;
222         *y -= ar->winrct.ymin;
223 }
224
225 void ui_region_to_window(const ARegion *ar, int *x, int *y)
226 {
227         *x += ar->winrct.xmin;
228         *y += ar->winrct.ymin;
229 }
230
231 static void ui_update_flexible_spacing(const ARegion *region, uiBlock *block)
232 {
233         int sepr_flex_len = 0;
234         for (uiBut *but = block->buttons.first; but; but = but->next) {
235                 if (but->type == UI_BTYPE_SEPR_SPACER) {
236                         sepr_flex_len++;
237                 }
238         }
239
240         if (sepr_flex_len == 0) {
241                 return;
242         }
243
244         rcti rect;
245         ui_but_to_pixelrect(&rect, region, block, block->buttons.last);
246         const float buttons_width = (float)rect.xmax + UI_HEADER_OFFSET;
247         const float region_width = (float)region->sizex * U.dpi_fac;
248
249         if (region_width <= buttons_width) {
250                 return;
251         }
252
253         /* We could get rid of this loop if we agree on a max number of spacer */
254         int *spacers_pos = alloca(sizeof(*spacers_pos) * (size_t)sepr_flex_len);
255         int i = 0;
256         for (uiBut *but = block->buttons.first; but; but = but->next) {
257                 if (but->type == UI_BTYPE_SEPR_SPACER) {
258                         ui_but_to_pixelrect(&rect, region, block, but);
259                         spacers_pos[i] = rect.xmax + UI_HEADER_OFFSET;
260                         i++;
261                 }
262         }
263
264         const float segment_width = region_width / (float)sepr_flex_len;
265         float offset = 0, remaining_space = region_width - buttons_width;
266         i = 0;
267         for (uiBut *but = block->buttons.first; but; but = but->next) {
268                 BLI_rctf_translate(&but->rect, offset, 0);
269                 if (but->type == UI_BTYPE_SEPR_SPACER) {
270                         /* How much the next block overlap with the current segment */
271                         int overlap = (
272                                 (i == sepr_flex_len - 1) ?
273                                 buttons_width - spacers_pos[i] :
274                                 (spacers_pos[i + 1] - spacers_pos[i]) / 2);
275                         int segment_end = segment_width * (i + 1);
276                         int spacer_end = segment_end - overlap;
277                         int spacer_sta = spacers_pos[i] + offset;
278                         if (spacer_end > spacer_sta) {
279                                 float step = min_ff(remaining_space, spacer_end - spacer_sta);
280                                 remaining_space -= step;
281                                 offset += step;
282                         }
283                         i++;
284                 }
285         }
286         ui_block_bounds_calc(block);
287 }
288
289 static void ui_update_window_matrix(const wmWindow *window, const ARegion *region, uiBlock *block)
290 {
291         /* window matrix and aspect */
292         if (region && region->visible) {
293                 /* Get projection matrix which includes View2D translation and zoom. */
294                 gpuGetProjectionMatrix(block->winmat);
295                 block->aspect = 2.0f / fabsf(region->winx * block->winmat[0][0]);
296         }
297         else {
298                 /* No subwindow created yet, for menus for example, so we use the main
299                  * window instead, since buttons are created there anyway. */
300                 int width = WM_window_pixels_x(window);
301                 int height = WM_window_pixels_y(window);
302                 rcti winrct = {0, width - 1, 0, height - 1};
303
304                 wmGetProjectionMatrix(block->winmat, &winrct);
305                 block->aspect = 2.0f / fabsf(width * block->winmat[0][0]);
306         }
307 }
308
309 /**
310  * Popups will add a margin to #ARegion.winrct for shadow,
311  * for interactivity (point-inside tests for eg), we want the winrct without the margin added.
312  */
313 void ui_region_winrct_get_no_margin(const struct ARegion *ar, struct rcti *r_rect)
314 {
315         uiBlock *block = ar->uiblocks.first;
316         if (block && (block->flag & UI_BLOCK_LOOP) && (block->flag & UI_BLOCK_RADIAL) == 0) {
317                 BLI_rcti_rctf_copy_floor(r_rect, &block->rect);
318                 BLI_rcti_translate(r_rect, ar->winrct.xmin, ar->winrct.ymin);
319         }
320         else {
321                 *r_rect = ar->winrct;
322         }
323 }
324
325 /* ******************* block calc ************************* */
326
327 void UI_block_translate(uiBlock *block, int x, int y)
328 {
329         uiBut *but;
330
331         for (but = block->buttons.first; but; but = but->next) {
332                 BLI_rctf_translate(&but->rect, x, y);
333         }
334
335         BLI_rctf_translate(&block->rect, x, y);
336 }
337
338 static void ui_block_bounds_calc_text(uiBlock *block, float offset)
339 {
340         uiStyle *style = UI_style_get();
341         uiBut *bt, *init_col_bt, *col_bt;
342         int i = 0, j, x1addval = offset;
343
344         UI_fontstyle_set(&style->widget);
345
346         for (init_col_bt = bt = block->buttons.first; bt; bt = bt->next) {
347                 if (!ELEM(bt->type, UI_BTYPE_SEPR, UI_BTYPE_SEPR_LINE, UI_BTYPE_SEPR_SPACER)) {
348                         j = BLF_width(style->widget.uifont_id, bt->drawstr, sizeof(bt->drawstr));
349
350                         if (j > i)
351                                 i = j;
352                 }
353
354                 if (bt->next && bt->rect.xmin < bt->next->rect.xmin) {
355                         /* End of this column, and it's not the last one. */
356                         for (col_bt = init_col_bt; col_bt->prev != bt; col_bt = col_bt->next) {
357                                 col_bt->rect.xmin = x1addval;
358                                 col_bt->rect.xmax = x1addval + i + block->bounds;
359
360                                 ui_but_update(col_bt);  /* clips text again */
361                         }
362
363                         /* And we prepare next column. */
364                         x1addval += i + block->bounds;
365                         i = 0;
366                         init_col_bt = col_bt;
367                 }
368         }
369
370         /* Last column. */
371         for (col_bt = init_col_bt; col_bt; col_bt = col_bt->next) {
372                 col_bt->rect.xmin = x1addval;
373                 col_bt->rect.xmax = max_ff(x1addval + i + block->bounds, offset + block->minbounds);
374
375                 ui_but_update(col_bt);  /* clips text again */
376         }
377 }
378
379 void ui_block_bounds_calc(uiBlock *block)
380 {
381         uiBut *bt;
382         int xof;
383
384         if (BLI_listbase_is_empty(&block->buttons)) {
385                 if (block->panel) {
386                         block->rect.xmin = 0.0; block->rect.xmax = block->panel->sizex;
387                         block->rect.ymin = 0.0; block->rect.ymax = block->panel->sizey;
388                 }
389         }
390         else {
391
392                 BLI_rctf_init_minmax(&block->rect);
393
394                 for (bt = block->buttons.first; bt; bt = bt->next) {
395                         BLI_rctf_union(&block->rect, &bt->rect);
396                 }
397
398                 block->rect.xmin -= block->bounds;
399                 block->rect.ymin -= block->bounds;
400                 block->rect.xmax += block->bounds;
401                 block->rect.ymax += block->bounds;
402         }
403
404         block->rect.xmax = block->rect.xmin + max_ff(BLI_rctf_size_x(&block->rect), block->minbounds);
405
406         /* hardcoded exception... but that one is annoying with larger safety */
407         bt = block->buttons.first;
408         if (bt && STREQLEN(bt->str, "ERROR", 5)) xof = 10;
409         else xof = 40;
410
411         block->safety.xmin = block->rect.xmin - xof;
412         block->safety.ymin = block->rect.ymin - xof;
413         block->safety.xmax = block->rect.xmax + xof;
414         block->safety.ymax = block->rect.ymax + xof;
415 }
416
417 static void ui_block_bounds_calc_centered(wmWindow *window, uiBlock *block)
418 {
419         int xmax, ymax;
420         int startx, starty;
421         int width, height;
422
423         /* note: this is used for the splash where window bounds event has not been
424          * updated by ghost, get the window bounds from ghost directly */
425
426         xmax = WM_window_pixels_x(window);
427         ymax = WM_window_pixels_y(window);
428
429         ui_block_bounds_calc(block);
430
431         width  = BLI_rctf_size_x(&block->rect);
432         height = BLI_rctf_size_y(&block->rect);
433
434         startx = (xmax * 0.5f) - (width * 0.5f);
435         starty = (ymax * 0.5f) - (height * 0.5f);
436
437         UI_block_translate(block, startx - block->rect.xmin, starty - block->rect.ymin);
438
439         /* now recompute bounds and safety */
440         ui_block_bounds_calc(block);
441
442 }
443
444 static void ui_block_bounds_calc_centered_pie(uiBlock *block)
445 {
446         const int xy[2] = {
447             block->pie_data.pie_center_spawned[0],
448             block->pie_data.pie_center_spawned[1]
449         };
450
451         UI_block_translate(block, xy[0], xy[1]);
452
453         /* now recompute bounds and safety */
454         ui_block_bounds_calc(block);
455 }
456
457 static void ui_block_bounds_calc_popup(
458         wmWindow *window, uiBlock *block,
459         eBlockBoundsCalc bounds_calc, const int xy[2], int r_xy[2])
460 {
461         int width, height, oldwidth, oldheight;
462         int oldbounds, xmax, ymax, raw_x, raw_y;
463         const int margin = UI_SCREEN_MARGIN;
464         rcti rect, rect_bounds;
465         int ofs_dummy[2];
466
467         oldbounds = block->bounds;
468
469         /* compute mouse position with user defined offset */
470         ui_block_bounds_calc(block);
471
472         xmax = WM_window_pixels_x(window);
473         ymax = WM_window_pixels_y(window);
474
475         oldwidth  = BLI_rctf_size_x(&block->rect);
476         oldheight = BLI_rctf_size_y(&block->rect);
477
478         /* first we ensure wide enough text bounds */
479         if (bounds_calc == UI_BLOCK_BOUNDS_POPUP_MENU) {
480                 if (block->flag & UI_BLOCK_LOOP) {
481                         block->bounds = 2.5f * UI_UNIT_X;
482                         ui_block_bounds_calc_text(block, block->rect.xmin);
483                 }
484         }
485
486         /* next we recompute bounds */
487         block->bounds = oldbounds;
488         ui_block_bounds_calc(block);
489
490         /* and we adjust the position to fit within window */
491         width  = BLI_rctf_size_x(&block->rect);
492         height = BLI_rctf_size_y(&block->rect);
493
494         /* avoid divide by zero below, caused by calling with no UI, but better not crash */
495         oldwidth = oldwidth > 0 ? oldwidth : MAX2(1, width);
496         oldheight = oldheight > 0 ? oldheight : MAX2(1, height);
497
498         /* offset block based on mouse position, user offset is scaled
499          * along in case we resized the block in ui_block_bounds_calc_text */
500         raw_x = rect.xmin = xy[0] + block->rect.xmin + (block->mx * width) / oldwidth;
501         raw_y = rect.ymin = xy[1] + block->rect.ymin + (block->my * height) / oldheight;
502         rect.xmax = rect.xmin + width;
503         rect.ymax = rect.ymin + height;
504
505         rect_bounds.xmin = margin;
506         rect_bounds.ymin = margin;
507         rect_bounds.xmax = xmax - margin;
508         rect_bounds.ymax = ymax - UI_POPUP_MENU_TOP;
509
510         BLI_rcti_clamp(&rect, &rect_bounds, ofs_dummy);
511         UI_block_translate(block, rect.xmin - block->rect.xmin, rect.ymin - block->rect.ymin);
512
513         /* now recompute bounds and safety */
514         ui_block_bounds_calc(block);
515
516         /* If given, adjust input coordinates such that they would generate real final popup position.
517          * Needed to handle correctly floating panels once they have been dragged around, see T52999. */
518         if (r_xy) {
519                 r_xy[0] = xy[0] + block->rect.xmin - raw_x;
520                 r_xy[1] = xy[1] + block->rect.ymin - raw_y;
521         }
522 }
523
524 /* used for various cases */
525 void UI_block_bounds_set_normal(uiBlock *block, int addval)
526 {
527         if (block == NULL)
528                 return;
529
530         block->bounds = addval;
531         block->bounds_type = UI_BLOCK_BOUNDS;
532 }
533
534 /* used for pulldowns */
535 void UI_block_bounds_set_text(uiBlock *block, int addval)
536 {
537         block->bounds = addval;
538         block->bounds_type = UI_BLOCK_BOUNDS_TEXT;
539 }
540
541 /* used for block popups */
542 void UI_block_bounds_set_popup(uiBlock *block, int addval, int mx, int my)
543 {
544         block->bounds = addval;
545         block->bounds_type = UI_BLOCK_BOUNDS_POPUP_MOUSE;
546         block->mx = mx;
547         block->my = my;
548 }
549
550 /* used for menu popups */
551 void UI_block_bounds_set_menu(uiBlock *block, int addval, int mx, int my)
552 {
553         block->bounds = addval;
554         block->bounds_type = UI_BLOCK_BOUNDS_POPUP_MENU;
555         block->mx = mx;
556         block->my = my;
557 }
558
559 /* used for centered popups, i.e. splash */
560 void UI_block_bounds_set_centered(uiBlock *block, int addval)
561 {
562         block->bounds = addval;
563         block->bounds_type = UI_BLOCK_BOUNDS_POPUP_CENTER;
564 }
565
566 void UI_block_bounds_set_explicit(uiBlock *block, int minx, int miny, int maxx, int maxy)
567 {
568         block->rect.xmin = minx;
569         block->rect.ymin = miny;
570         block->rect.xmax = maxx;
571         block->rect.ymax = maxy;
572         block->bounds_type = UI_BLOCK_BOUNDS_NONE;
573 }
574
575 static int ui_but_calc_float_precision(uiBut *but, double value)
576 {
577         int prec = (int)but->a2;
578
579         /* first check for various special cases:
580          * * If button is radians, we want additional precision (see T39861).
581          * * If prec is not set, we fallback to a simple default */
582         if (ui_but_is_unit_radians(but) && prec < 5) {
583                 prec = 5;
584         }
585         else if (prec == -1) {
586                 prec = (but->hardmax < 10.001f) ? 3 : 2;
587         }
588         else {
589                 CLAMP(prec, 0, UI_PRECISION_FLOAT_MAX);
590         }
591
592         return UI_calc_float_precision(prec, value);
593 }
594
595 /* ************** BLOCK ENDING FUNCTION ************* */
596
597 /* NOTE: if but->poin is allocated memory for every defbut, things fail... */
598 static bool ui_but_equals_old(const uiBut *but, const uiBut *oldbut)
599 {
600         /* various properties are being compared here, hopefully sufficient
601          * to catch all cases, but it is simple to add more checks later */
602         if (but->retval != oldbut->retval) return false;
603         if (but->rnapoin.data != oldbut->rnapoin.data) return false;
604         if (but->rnaprop != oldbut->rnaprop || but->rnaindex != oldbut->rnaindex) return false;
605         if (but->func != oldbut->func) return false;
606         if (but->funcN != oldbut->funcN) return false;
607         if (oldbut->func_arg1 != oldbut && but->func_arg1 != oldbut->func_arg1) return false;
608         if (oldbut->func_arg2 != oldbut && but->func_arg2 != oldbut->func_arg2) return false;
609         if (!but->funcN && ((but->poin != oldbut->poin && (uiBut *)oldbut->poin != oldbut) ||
610                             (but->pointype != oldbut->pointype))) return false;
611         if (but->optype != oldbut->optype) return false;
612
613         return true;
614 }
615
616 uiBut *ui_but_find_old(uiBlock *block_old, const uiBut *but_new)
617 {
618         uiBut *but_old;
619         for (but_old = block_old->buttons.first; but_old; but_old = but_old->next) {
620                 if (ui_but_equals_old(but_new, but_old)) {
621                         break;
622                 }
623         }
624         return but_old;
625 }
626 uiBut *ui_but_find_new(uiBlock *block_new, const uiBut *but_old)
627 {
628         uiBut *but_new;
629         for (but_new = block_new->buttons.first; but_new; but_new = but_new->next) {
630                 if (ui_but_equals_old(but_new, but_old)) {
631                         break;
632                 }
633         }
634         return but_new;
635 }
636
637 /**
638  * \return true when \a but_p is set (only done for active buttons).
639  */
640 static bool ui_but_update_from_old_block(const bContext *C, uiBlock *block, uiBut **but_p, uiBut **but_old_p)
641 {
642         const int drawflag_copy = 0;  /* None currently. */
643
644         uiBlock *oldblock = block->oldblock;
645         uiBut *oldbut = NULL, *but = *but_p;
646         bool found_active = false;
647
648
649 #if 0
650         /* simple/stupid - search every time */
651         oldbut = ui_but_find_old(oldblock, but);
652         (void)but_old_p;
653 #else
654         BLI_assert(*but_old_p == NULL || BLI_findindex(&oldblock->buttons, *but_old_p) != -1);
655
656         /* fastpath - avoid loop-in-loop, calling 'ui_but_find_old'
657          * as long as old/new buttons are aligned */
658         if (LIKELY(*but_old_p && ui_but_equals_old(but, *but_old_p))) {
659                 oldbut = *but_old_p;
660         }
661         else {
662                 /* fallback to block search */
663                 oldbut = ui_but_find_old(oldblock, but);
664         }
665         (*but_old_p) = oldbut ? oldbut->next : NULL;
666 #endif
667
668
669         if (!oldbut) {
670                 return found_active;
671         }
672
673         if (oldbut->active) {
674                 /* flags from the buttons we want to refresh, may want to add more here... */
675                 const int flag_copy = UI_BUT_REDALERT | UI_HAS_ICON;
676
677                 found_active = true;
678
679 #if 0
680                 but->flag = oldbut->flag;
681                 but->active = oldbut->active;
682                 but->pos = oldbut->pos;
683                 but->ofs = oldbut->ofs;
684                 but->editstr = oldbut->editstr;
685                 but->editval = oldbut->editval;
686                 but->editvec = oldbut->editvec;
687                 but->editcoba = oldbut->editcoba;
688                 but->editcumap = oldbut->editcumap;
689                 but->selsta = oldbut->selsta;
690                 but->selend = oldbut->selend;
691                 but->softmin = oldbut->softmin;
692                 but->softmax = oldbut->softmax;
693                 oldbut->active = NULL;
694 #endif
695
696                 /* move button over from oldblock to new block */
697                 BLI_remlink(&oldblock->buttons, oldbut);
698                 BLI_insertlinkafter(&block->buttons, but, oldbut);
699                 oldbut->block = block;
700                 *but_p = oldbut;
701
702                 /* still stuff needs to be copied */
703                 oldbut->rect = but->rect;
704                 oldbut->context = but->context; /* set by Layout */
705
706                 /* drawing */
707                 oldbut->icon = but->icon;
708                 oldbut->iconadd = but->iconadd;
709                 oldbut->alignnr = but->alignnr;
710
711                 /* typically the same pointers, but not on undo/redo */
712                 /* XXX some menu buttons store button itself in but->poin. Ugly */
713                 if (oldbut->poin != (char *)oldbut) {
714                         SWAP(char *, oldbut->poin, but->poin);
715                         SWAP(void *, oldbut->func_argN, but->func_argN);
716                         SWAP(void *, oldbut->tip_argN, but->tip_argN);
717                 }
718
719                 oldbut->flag = (oldbut->flag & ~flag_copy) | (but->flag & flag_copy);
720                 oldbut->drawflag = (oldbut->drawflag & ~drawflag_copy) | (but->drawflag & drawflag_copy);
721
722                 /* copy hardmin for list rows to prevent 'sticking' highlight to mouse position
723                  * when scrolling without moving mouse (see [#28432]) */
724                 if (ELEM(oldbut->type, UI_BTYPE_ROW, UI_BTYPE_LISTROW)) {
725                         oldbut->hardmax = but->hardmax;
726                 }
727
728                 /* Selectively copy a1, a2 since their use differs across all button types
729                  * (and we'll probably split these out later) */
730                 if (ELEM(oldbut->type, UI_BTYPE_PROGRESS_BAR)) {
731                         oldbut->a1 = but->a1;
732                 }
733
734                 if (!BLI_listbase_is_empty(&block->butstore)) {
735                         UI_butstore_register_update(block, oldbut, but);
736                 }
737
738                 /* move/copy string from the new button to the old */
739                 /* needed for alt+mouse wheel over enums */
740                 if (but->str != but->strdata) {
741                         if (oldbut->str != oldbut->strdata) {
742                                 SWAP(char *, but->str, oldbut->str);
743                         }
744                         else {
745                                 oldbut->str = but->str;
746                                 but->str = but->strdata;
747                         }
748                 }
749                 else {
750                         if (oldbut->str != oldbut->strdata) {
751                                 MEM_freeN(oldbut->str);
752                                 oldbut->str = oldbut->strdata;
753                         }
754                         BLI_strncpy(oldbut->strdata, but->strdata, sizeof(oldbut->strdata));
755                 }
756
757                 if (but->dragpoin && (but->dragflag & UI_BUT_DRAGPOIN_FREE)) {
758                         SWAP(void *, but->dragpoin, oldbut->dragpoin);
759                 }
760
761                 BLI_remlink(&block->buttons, but);
762                 ui_but_free(C, but);
763
764                 /* note: if layout hasn't been applied yet, it uses old button pointers... */
765         }
766         else {
767                 const int flag_copy = UI_BUT_DRAG_MULTI;
768
769                 but->flag = (but->flag & ~flag_copy) | (oldbut->flag & flag_copy);
770
771                 /* ensures one button can get activated, and in case the buttons
772                  * draw are the same this gives O(1) lookup for each button */
773                 BLI_remlink(&oldblock->buttons, oldbut);
774                 ui_but_free(C, oldbut);
775         }
776
777         return found_active;
778 }
779
780 /* needed for temporarily rename buttons, such as in outliner or file-select,
781  * they should keep calling uiDefButs to keep them alive */
782 /* returns 0 when button removed */
783 bool UI_but_active_only(const bContext *C, ARegion *ar, uiBlock *block, uiBut *but)
784 {
785         uiBlock *oldblock;
786         uiBut *oldbut;
787         bool activate = false, found = false, isactive = false;
788
789         oldblock = block->oldblock;
790         if (!oldblock) {
791                 activate = true;
792         }
793         else {
794                 oldbut = ui_but_find_old(oldblock, but);
795                 if (oldbut) {
796                         found = true;
797
798                         if (oldbut->active) {
799                                 isactive = true;
800                         }
801                 }
802         }
803         if ((activate == true) || (found == false)) {
804                 ui_but_activate_event((bContext *)C, ar, but);
805         }
806         else if ((found == true) && (isactive == false)) {
807                 BLI_remlink(&block->buttons, but);
808                 ui_but_free(C, but);
809                 return false;
810         }
811
812         return true;
813 }
814
815 /* simulate button click */
816 void UI_but_execute(const bContext *C, uiBut *but)
817 {
818         ARegion *ar = CTX_wm_region(C);
819         void *active_back;
820         ui_but_execute_begin((bContext *)C, ar, but, &active_back);
821         /* Value is applied in begin. No further action required. */
822         ui_but_execute_end((bContext *)C, ar, but, active_back);
823 }
824
825 /* use to check if we need to disable undo, but don't make any changes
826  * returns false if undo needs to be disabled. */
827 static bool ui_but_is_rna_undo(const uiBut *but)
828 {
829         if (but->rnapoin.id.data) {
830                 /* avoid undo push for buttons who's ID are screen or wm level
831                  * we could disable undo for buttons with no ID too but may have
832                  * unforeseen consequences, so best check for ID's we _know_ are not
833                  * handled by undo - campbell */
834                 ID *id = but->rnapoin.id.data;
835                 if (ID_CHECK_UNDO(id) == false) {
836                         return false;
837                 }
838                 else {
839                         return true;
840                 }
841         }
842         else if (but->rnapoin.type && !RNA_struct_undo_check(but->rnapoin.type)) {
843                 return false;
844         }
845
846         return true;
847 }
848
849 /* assigns automatic keybindings to menu items for fast access
850  * (underline key in menu) */
851 static void ui_menu_block_set_keyaccels(uiBlock *block)
852 {
853         uiBut *but;
854
855         unsigned int menu_key_mask = 0;
856         unsigned char menu_key;
857         const char *str_pt;
858         int pass;
859         int tot_missing = 0;
860
861         /* only do it before bounding */
862         if (block->rect.xmin != block->rect.xmax)
863                 return;
864
865         for (pass = 0; pass < 2; pass++) {
866                 /* 2 Passes, on for first letter only, second for any letter if first fails
867                  * fun first pass on all buttons so first word chars always get first priority */
868
869                 for (but = block->buttons.first; but; but = but->next) {
870                         if (!ELEM(but->type,
871                                   UI_BTYPE_BUT,
872                                   UI_BTYPE_BUT_MENU,
873                                   UI_BTYPE_MENU, UI_BTYPE_BLOCK,
874                                   UI_BTYPE_PULLDOWN) ||
875                             (but->flag & UI_HIDDEN))
876                         {
877                                 /* pass */
878                         }
879                         else if (but->menu_key == '\0') {
880                                 if (but->str) {
881                                         for (str_pt = but->str; *str_pt; ) {
882                                                 menu_key = tolower(*str_pt);
883                                                 if ((menu_key >= 'a' && menu_key <= 'z') && !(menu_key_mask & 1 << (menu_key - 'a'))) {
884                                                         menu_key_mask |= 1 << (menu_key - 'a');
885                                                         break;
886                                                 }
887
888                                                 if (pass == 0) {
889                                                         /* Skip to next delimiter on first pass (be picky) */
890                                                         while (isalpha(*str_pt))
891                                                                 str_pt++;
892
893                                                         if (*str_pt)
894                                                                 str_pt++;
895                                                 }
896                                                 else {
897                                                         /* just step over every char second pass and find first usable key */
898                                                         str_pt++;
899                                                 }
900                                         }
901
902                                         if (*str_pt) {
903                                                 but->menu_key = menu_key;
904                                         }
905                                         else {
906                                                 /* run second pass */
907                                                 tot_missing++;
908                                         }
909
910                                         /* if all keys have been used just exit, unlikely */
911                                         if (menu_key_mask == (1 << 26) - 1) {
912                                                 return;
913                                         }
914                                 }
915                         }
916                 }
917
918                 /* check if second pass is needed */
919                 if (!tot_missing) {
920                         break;
921                 }
922         }
923 }
924
925 /* XXX, this code will shorten any allocated string to 'UI_MAX_NAME_STR'
926  * since this is really long its unlikely to be an issue,
927  * but this could be supported */
928 void ui_but_add_shortcut(uiBut *but, const char *shortcut_str, const bool do_strip)
929 {
930
931         if (do_strip && (but->flag & UI_BUT_HAS_SEP_CHAR)) {
932                 char *cpoin = strrchr(but->str, UI_SEP_CHAR);
933                 if (cpoin) {
934                         *cpoin = '\0';
935                 }
936                 but->flag &= ~UI_BUT_HAS_SEP_CHAR;
937         }
938
939         /* without this, just allow stripping of the shortcut */
940         if (shortcut_str) {
941                 char *butstr_orig;
942
943                 if (but->str != but->strdata) {
944                         butstr_orig = but->str; /* free after using as source buffer */
945                 }
946                 else {
947                         butstr_orig = BLI_strdup(but->str);
948                 }
949                 BLI_snprintf(but->strdata,
950                              sizeof(but->strdata),
951                              "%s" UI_SEP_CHAR_S "%s",
952                              butstr_orig, shortcut_str);
953                 MEM_freeN(butstr_orig);
954                 but->str = but->strdata;
955                 but->flag |= UI_BUT_HAS_SEP_CHAR;
956                 ui_but_update(but);
957         }
958 }
959
960 static bool ui_but_event_operator_string(
961         const bContext *C, uiBut *but,
962         char *buf, const size_t buf_len)
963 {
964         MenuType *mt;
965         bool found = false;
966
967         if (but->optype) {
968                 IDProperty *prop = (but->opptr) ? but->opptr->data : NULL;
969
970                 if (WM_key_event_operator_string(
971                         C, but->optype->idname, but->opcontext, prop, true,
972                         buf, buf_len))
973                 {
974                         found = true;
975                 }
976         }
977         else if ((mt = UI_but_menutype_get(but))) {
978                 IDProperty *prop_menu;
979                 IDProperty *prop_menu_name;
980
981                 /* annoying, create a property */
982                 IDPropertyTemplate val = {0};
983                 prop_menu = IDP_New(IDP_GROUP, &val, __func__); /* dummy, name is unimportant  */
984                 IDP_AddToGroup(prop_menu, (prop_menu_name = IDP_NewString("", "name", sizeof(mt->idname))));
985
986                 IDP_AssignString(prop_menu_name, mt->idname, sizeof(mt->idname));
987
988                 if (WM_key_event_operator_string(
989                         C, "WM_OT_call_menu", WM_OP_INVOKE_REGION_WIN, prop_menu, true,
990                         buf, buf_len))
991                 {
992                         found = true;
993                 }
994
995                 IDP_FreeProperty(prop_menu);
996                 MEM_freeN(prop_menu);
997         }
998
999         return found;
1000 }
1001
1002 static bool ui_but_event_property_operator_string(
1003         const bContext *C, uiBut *but,
1004         char *buf, const size_t buf_len)
1005 {
1006         /* context toggle operator names to check... */
1007         const char *ctx_toggle_opnames[] = {
1008                 "WM_OT_context_toggle",
1009                 "WM_OT_context_toggle_enum",
1010                 "WM_OT_context_cycle_int",
1011                 "WM_OT_context_cycle_enum",
1012                 "WM_OT_context_cycle_array",
1013                 "WM_OT_context_menu_enum",
1014                 NULL
1015         };
1016         const size_t num_ops = sizeof(ctx_toggle_opnames) / sizeof(const char *);
1017
1018         bool found = false;
1019
1020         /* this version is only for finding hotkeys for properties (which get set via context using operators) */
1021         if (but->rnaprop) {
1022                 /* to avoid massive slowdowns on property panels, for now, we only check the
1023                  * hotkeys for Editor / Scene settings...
1024                  *
1025                  * TODO: userpref settings?
1026                  */
1027                 // TODO: value (for enum stuff)?
1028                 char *data_path = NULL;
1029
1030                 if (but->rnapoin.id.data) {
1031                         ID *id = but->rnapoin.id.data;
1032
1033                         if (GS(id->name) == ID_SCR) {
1034                                 /* screen/editor property
1035                                  * NOTE: in most cases, there is actually no info for backwards tracing
1036                                  * how to get back to ID from the editor data we may be dealing with
1037                                  */
1038                                 if (RNA_struct_is_a(but->rnapoin.type, &RNA_Space)) {
1039                                         /* data should be directly on here... */
1040                                         data_path = BLI_sprintfN("space_data.%s", RNA_property_identifier(but->rnaprop));
1041                                 }
1042                                 else {
1043                                         /* special exceptions for common nested data in editors... */
1044                                         if (RNA_struct_is_a(but->rnapoin.type, &RNA_DopeSheet)) {
1045                                                 /* dopesheet filtering options... */
1046                                                 data_path = BLI_sprintfN("space_data.dopesheet.%s", RNA_property_identifier(but->rnaprop));
1047                                         }
1048                                         else if (RNA_struct_is_a(but->rnapoin.type, &RNA_FileSelectParams)) {
1049                                                 /* Filebrowser options... */
1050                                                 data_path = BLI_sprintfN("space_data.params.%s", RNA_property_identifier(but->rnaprop));
1051                                         }
1052                                 }
1053                         }
1054                         else if (GS(id->name) == ID_SCE) {
1055                                 if (RNA_struct_is_a(but->rnapoin.type, &RNA_ToolSettings)) {
1056                                         /* toolsettings property
1057                                          * NOTE: toolsettings is usually accessed directly (i.e. not through scene)
1058                                          */
1059                                         data_path = RNA_path_from_ID_to_property(&but->rnapoin, but->rnaprop);
1060                                 }
1061                                 else {
1062                                         /* scene property */
1063                                         char *path = RNA_path_from_ID_to_property(&but->rnapoin, but->rnaprop);
1064
1065                                         if (path) {
1066                                                 data_path = BLI_sprintfN("scene.%s", path);
1067                                                 MEM_freeN(path);
1068                                         }
1069 #if 0
1070                                         else {
1071                                                 printf("ERROR in %s(): Couldn't get path for scene property - %s\n",
1072                                                        __func__, RNA_property_identifier(but->rnaprop));
1073                                         }
1074 #endif
1075                                 }
1076                         }
1077                         else {
1078                                 //puts("other id");
1079                         }
1080
1081                         //printf("prop shortcut: '%s' (%s)\n", RNA_property_identifier(but->rnaprop), data_path);
1082                 }
1083
1084                 /* we have a datapath! */
1085                 if (data_path) {
1086                         size_t i;
1087
1088                         /* create a property to host the "datapath" property we're sending to the operators */
1089                         IDProperty *prop_path;
1090                         IDProperty *prop_path_value;
1091
1092                         IDPropertyTemplate val = {0};
1093                         prop_path = IDP_New(IDP_GROUP, &val, __func__);
1094                         prop_path_value = IDP_NewString(data_path, "data_path", strlen(data_path) + 1);
1095                         IDP_AddToGroup(prop_path, prop_path_value);
1096
1097                         /* check each until one works... */
1098                         for (i = 0; (i < num_ops) && (ctx_toggle_opnames[i]); i++) {
1099                                 if (WM_key_event_operator_string(
1100                                         C, ctx_toggle_opnames[i], WM_OP_INVOKE_REGION_WIN, prop_path, false,
1101                                         buf, buf_len))
1102                                 {
1103                                         found = true;
1104                                         break;
1105                                 }
1106                         }
1107
1108                         /* cleanup */
1109                         IDP_FreeProperty(prop_path);
1110                         MEM_freeN(prop_path);
1111                         MEM_freeN(data_path);
1112                 }
1113         }
1114
1115         return found;
1116 }
1117
1118 /**
1119  * This goes in a seemingly weird pattern:
1120  *
1121  * <pre>
1122  *     4
1123  *  5     6
1124  * 1       2
1125  *  7     8
1126  *     3
1127  * </pre>
1128  *
1129  * but it's actually quite logical. It's designed to be 'upwards compatible'
1130  * for muscle memory so that the menu item locations are fixed and don't move
1131  * as new items are added to the menu later on. It also optimises efficiency -
1132  * a radial menu is best kept symmetrical, with as large an angle between
1133  * items as possible, so that the gestural mouse movements can be fast and inexact.
1134  *
1135  * It starts off with two opposite sides for the first two items
1136  * then joined by the one below for the third (this way, even with three items,
1137  * the menu seems to still be 'in order' reading left to right). Then the fourth is
1138  * added to complete the compass directions. From here, it's just a matter of
1139  * subdividing the rest of the angles for the last 4 items.
1140  *
1141  * --Matt 07/2006
1142  */
1143 const char ui_radial_dir_order[8] = {
1144     UI_RADIAL_W,  UI_RADIAL_E,  UI_RADIAL_S,  UI_RADIAL_N,
1145     UI_RADIAL_NW, UI_RADIAL_NE, UI_RADIAL_SW, UI_RADIAL_SE};
1146
1147 const char  ui_radial_dir_to_numpad[8] = {8, 9, 6, 3, 2, 1, 4, 7};
1148 const short ui_radial_dir_to_angle[8] =  {90, 45, 0, 315, 270, 225, 180, 135};
1149
1150 static void ui_but_pie_direction_string(uiBut *but, char *buf, int size)
1151 {
1152         BLI_assert(but->pie_dir < ARRAY_SIZE(ui_radial_dir_to_numpad));
1153         BLI_snprintf(buf, size, "%d", ui_radial_dir_to_numpad[but->pie_dir]);
1154 }
1155
1156 static void ui_menu_block_set_keymaps(const bContext *C, uiBlock *block)
1157 {
1158         uiBut *but;
1159         char buf[128];
1160
1161         BLI_assert(block->flag & (UI_BLOCK_LOOP | UI_BLOCK_SHOW_SHORTCUT_ALWAYS));
1162
1163         /* only do it before bounding */
1164         if (block->rect.xmin != block->rect.xmax)
1165                 return;
1166
1167         if (block->flag & UI_BLOCK_RADIAL) {
1168                 for (but = block->buttons.first; but; but = but->next) {
1169                         if (but->pie_dir != UI_RADIAL_NONE) {
1170                                 ui_but_pie_direction_string(but, buf, sizeof(buf));
1171                                 ui_but_add_shortcut(but, buf, false);
1172                         }
1173                 }
1174         }
1175         else {
1176                 for (but = block->buttons.first; but; but = but->next) {
1177                         if (block->flag & UI_BLOCK_SHOW_SHORTCUT_ALWAYS) {
1178                                 /* Skip icon-only buttons (as used in the toolbar). */
1179                                 if (but->drawstr[0] == '\0') {
1180                                         continue;
1181                                 }
1182                         }
1183                         else if (but->dt != UI_EMBOSS_PULLDOWN) {
1184                                 continue;
1185                         }
1186
1187                         if (ui_but_event_operator_string(C, but, buf, sizeof(buf))) {
1188                                 ui_but_add_shortcut(but, buf, false);
1189                         }
1190                         else if (ui_but_event_property_operator_string(C, but, buf, sizeof(buf))) {
1191                                 ui_but_add_shortcut(but, buf, false);
1192                         }
1193                 }
1194         }
1195 }
1196
1197 void ui_but_override_flag(uiBut *but)
1198 {
1199         const int override_status = RNA_property_static_override_status(&but->rnapoin, but->rnaprop, but->rnaindex);
1200
1201         if (override_status & RNA_OVERRIDE_STATUS_OVERRIDDEN) {
1202                 but->flag |= UI_BUT_OVERRIDEN;
1203         }
1204         else {
1205                 but->flag &= ~UI_BUT_OVERRIDEN;
1206         }
1207 }
1208
1209 void UI_block_update_from_old(const bContext *C, uiBlock *block)
1210 {
1211         uiBut *but_old;
1212         uiBut *but;
1213
1214         if (!block->oldblock)
1215                 return;
1216
1217         but_old = block->oldblock->buttons.first;
1218
1219         if (BLI_listbase_is_empty(&block->oldblock->butstore) == false) {
1220                 UI_butstore_update(block);
1221         }
1222
1223         for (but = block->buttons.first; but; but = but->next) {
1224                 if (ui_but_update_from_old_block(C, block, &but, &but_old)) {
1225                         ui_but_update(but);
1226
1227                         /* redraw dynamic tooltip if we have one open */
1228                         if (but->tip_func) {
1229                                 UI_but_tooltip_refresh((bContext *)C, but);
1230                         }
1231                 }
1232         }
1233
1234         block->auto_open = block->oldblock->auto_open;
1235         block->auto_open_last = block->oldblock->auto_open_last;
1236         block->tooltipdisabled = block->oldblock->tooltipdisabled;
1237         BLI_movelisttolist(&block->color_pickers.list, &block->oldblock->color_pickers.list);
1238
1239         block->oldblock = NULL;
1240 }
1241
1242 void UI_block_end_ex(const bContext *C, uiBlock *block, const int xy[2], int r_xy[2])
1243 {
1244         wmWindow *window = CTX_wm_window(C);
1245         Scene *scene = CTX_data_scene(C);
1246         ARegion *region = CTX_wm_region(C);
1247         uiBut *but;
1248
1249         BLI_assert(block->active);
1250
1251         UI_block_update_from_old(C, block);
1252
1253         /* inherit flags from 'old' buttons that was drawn here previous, based
1254          * on matching buttons, we need this to make button event handling non
1255          * blocking, while still allowing buttons to be remade each redraw as it
1256          * is expected by blender code */
1257         for (but = block->buttons.first; but; but = but->next) {
1258                 /* temp? Proper check for graying out */
1259                 if (but->optype) {
1260                         wmOperatorType *ot = but->optype;
1261
1262                         if (but->context)
1263                                 CTX_store_set((bContext *)C, but->context);
1264
1265                         if (ot == NULL || WM_operator_poll_context((bContext *)C, ot, but->opcontext) == 0) {
1266                                 but->flag |= UI_BUT_DISABLED;
1267                         }
1268
1269                         if (but->context)
1270                                 CTX_store_set((bContext *)C, NULL);
1271                 }
1272
1273                 ui_but_anim_flag(but, (scene) ? scene->r.cfra : 0.0f);
1274                 ui_but_override_flag(but);
1275                 if (UI_but_is_decorator(but)) {
1276                         ui_but_anim_decorate_update_from_flag(but);
1277                 }
1278         }
1279
1280
1281
1282         /* handle pending stuff */
1283         if (block->layouts.first) {
1284                 UI_block_layout_resolve(block, NULL, NULL);
1285         }
1286         ui_block_align_calc(block, CTX_wm_region(C));
1287         if ((block->flag & UI_BLOCK_LOOP) && (block->flag & UI_BLOCK_NUMSELECT)) {
1288                 ui_menu_block_set_keyaccels(block); /* could use a different flag to check */
1289         }
1290
1291         if (block->flag & (UI_BLOCK_LOOP | UI_BLOCK_SHOW_SHORTCUT_ALWAYS)) {
1292                 ui_menu_block_set_keymaps(C, block);
1293         }
1294
1295         /* after keymaps! */
1296         switch (block->bounds_type) {
1297                 case UI_BLOCK_BOUNDS_NONE:
1298                         break;
1299                 case UI_BLOCK_BOUNDS:
1300                         ui_block_bounds_calc(block);
1301                         break;
1302                 case UI_BLOCK_BOUNDS_TEXT:
1303                         ui_block_bounds_calc_text(block, 0.0f);
1304                         break;
1305                 case UI_BLOCK_BOUNDS_POPUP_CENTER:
1306                         ui_block_bounds_calc_centered(window, block);
1307                         break;
1308                 case UI_BLOCK_BOUNDS_PIE_CENTER:
1309                         ui_block_bounds_calc_centered_pie(block);
1310                         break;
1311
1312                         /* fallback */
1313                 case UI_BLOCK_BOUNDS_POPUP_MOUSE:
1314                 case UI_BLOCK_BOUNDS_POPUP_MENU:
1315                         ui_block_bounds_calc_popup(window, block, block->bounds_type, xy, r_xy);
1316                         break;
1317         }
1318
1319         if (block->rect.xmin == 0.0f && block->rect.xmax == 0.0f) {
1320                 UI_block_bounds_set_normal(block, 0);
1321         }
1322         if (block->flag & UI_BUT_ALIGN) {
1323                 UI_block_align_end(block);
1324         }
1325
1326         ui_update_flexible_spacing(region, block);
1327
1328         block->endblock = 1;
1329 }
1330
1331 void UI_block_end(const bContext *C, uiBlock *block)
1332 {
1333         wmWindow *window = CTX_wm_window(C);
1334
1335         UI_block_end_ex(C, block, &window->eventstate->x, NULL);
1336 }
1337
1338 /* ************** BLOCK DRAWING FUNCTION ************* */
1339
1340 void ui_fontscale(short *points, float aspect)
1341 {
1342         if (aspect < 0.9f || aspect > 1.1f) {
1343                 float pointsf = *points;
1344
1345                 /* for some reason scaling fonts goes too fast compared to widget size */
1346                 /* XXX not true anymore? (ton) */
1347                 //aspect = sqrt(aspect);
1348                 pointsf /= aspect;
1349
1350                 if (aspect > 1.0f)
1351                         *points = ceilf(pointsf);
1352                 else
1353                         *points = floorf(pointsf);
1354         }
1355 }
1356
1357 /* project button or block (but==NULL) to pixels in regionspace */
1358 static void ui_but_to_pixelrect(rcti *rect, const ARegion *ar, uiBlock *block, uiBut *but)
1359 {
1360         rctf rectf;
1361
1362         ui_block_to_window_rctf(ar, block, &rectf, (but) ? &but->rect : &block->rect);
1363         BLI_rcti_rctf_copy_round(rect, &rectf);
1364         BLI_rcti_translate(rect, -ar->winrct.xmin, -ar->winrct.ymin);
1365 }
1366
1367 /* uses local copy of style, to scale things down, and allow widgets to change stuff */
1368 void UI_block_draw(const bContext *C, uiBlock *block)
1369 {
1370         uiStyle style = *UI_style_get_dpi();  /* XXX pass on as arg */
1371         ARegion *ar;
1372         uiBut *but;
1373         rcti rect;
1374
1375         /* get menu region or area region */
1376         ar = CTX_wm_menu(C);
1377         if (!ar)
1378                 ar = CTX_wm_region(C);
1379
1380         if (!block->endblock)
1381                 UI_block_end(C, block);
1382
1383         /* we set this only once */
1384         glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
1385
1386         /* scale fonts */
1387         ui_fontscale(&style.paneltitle.points, block->aspect);
1388         ui_fontscale(&style.grouplabel.points, block->aspect);
1389         ui_fontscale(&style.widgetlabel.points, block->aspect);
1390         ui_fontscale(&style.widget.points, block->aspect);
1391
1392         /* scale block min/max to rect */
1393         ui_but_to_pixelrect(&rect, ar, block, NULL);
1394
1395         /* pixel space for AA widgets */
1396         gpuPushProjectionMatrix();
1397         gpuPushMatrix();
1398         gpuLoadIdentity();
1399
1400         wmOrtho2_region_pixelspace(ar);
1401
1402         /* back */
1403         if (block->flag & UI_BLOCK_RADIAL)
1404                 ui_draw_pie_center(block);
1405         else if (block->flag & UI_BLOCK_POPOVER)
1406                 ui_draw_popover_back(ar, &style, block, &rect);
1407         else if (block->flag & UI_BLOCK_LOOP)
1408                 ui_draw_menu_back(&style, block, &rect);
1409         else if (block->panel)
1410                 ui_draw_aligned_panel(&style, block, &rect, UI_panel_category_is_visible(ar));
1411
1412         BLF_batch_draw_begin();
1413         UI_icon_draw_cache_begin();
1414         UI_widgetbase_draw_cache_begin();
1415
1416         /* widgets */
1417         for (but = block->buttons.first; but; but = but->next) {
1418                 if (!(but->flag & (UI_HIDDEN | UI_SCROLLED))) {
1419                         ui_but_to_pixelrect(&rect, ar, block, but);
1420
1421                         /* XXX: figure out why invalid coordinates happen when closing render window */
1422                         /* and material preview is redrawn in main window (temp fix for bug #23848) */
1423                         if (rect.xmin < rect.xmax && rect.ymin < rect.ymax)
1424                                 ui_draw_but(C, ar, &style, but, &rect);
1425                 }
1426         }
1427
1428         UI_widgetbase_draw_cache_end();
1429         UI_icon_draw_cache_end();
1430         BLF_batch_draw_end();
1431
1432         /* restore matrix */
1433         gpuPopProjectionMatrix();
1434         gpuPopMatrix();
1435 }
1436
1437 static void ui_block_message_subscribe(ARegion *ar, struct wmMsgBus *mbus, uiBlock *block)
1438 {
1439         uiBut *but_prev = NULL;
1440         /* possibly we should keep the region this block is contained in? */
1441         for (uiBut *but = block->buttons.first; but; but = but->next) {
1442                 if (but->rnapoin.type && but->rnaprop) {
1443                         /* quick check to avoid adding buttons representing a vector, multiple times. */
1444                         if ((but_prev &&
1445                             (but_prev->rnaprop == but->rnaprop) &&
1446                             (but_prev->rnapoin.type == but->rnapoin.type) &&
1447                             (but_prev->rnapoin.data == but->rnapoin.data) &&
1448                             (but_prev->rnapoin.id.data == but->rnapoin.id.data)) == false)
1449                         {
1450                                 /* TODO: could make this into utility function. */
1451                                 WM_msg_subscribe_rna(
1452                                         mbus, &but->rnapoin, but->rnaprop,
1453                                         &(const wmMsgSubscribeValue){
1454                                             .owner = ar,
1455                                             .user_data = ar,
1456                                             .notify = ED_region_do_msg_notify_tag_redraw,
1457                                         }, __func__);
1458                                 but_prev = but;
1459                         }
1460                 }
1461         }
1462 }
1463
1464 void UI_region_message_subscribe(ARegion *ar, struct wmMsgBus *mbus)
1465 {
1466         for (uiBlock *block = ar->uiblocks.first; block; block = block->next) {
1467                 ui_block_message_subscribe(ar, mbus, block);
1468         }
1469 }
1470
1471 /* ************* EVENTS ************* */
1472
1473 /**
1474  * Check if the button is pushed, this is only meaningful for some button types.
1475  *
1476  * \return (0 == UNSELECT), (1 == SELECT), (-1 == DO-NOTHING)
1477  */
1478 int ui_but_is_pushed_ex(uiBut *but, double *value)
1479 {
1480         int is_push = 0;
1481
1482         if (but->bit) {
1483                 const bool state = ELEM(but->type, UI_BTYPE_TOGGLE_N, UI_BTYPE_ICON_TOGGLE_N, UI_BTYPE_CHECKBOX_N) ? false : true;
1484                 int lvalue;
1485                 UI_GET_BUT_VALUE_INIT(but, *value);
1486                 lvalue = (int)*value;
1487                 if (UI_BITBUT_TEST(lvalue, (but->bitnr))) {
1488                         is_push = state;
1489                 }
1490                 else {
1491                         is_push = !state;
1492                 }
1493         }
1494         else {
1495                 switch (but->type) {
1496                         case UI_BTYPE_BUT:
1497                         case UI_BTYPE_HOTKEY_EVENT:
1498                         case UI_BTYPE_KEY_EVENT:
1499                         case UI_BTYPE_COLOR:
1500                                 is_push = -1;
1501                                 break;
1502                         case UI_BTYPE_BUT_TOGGLE:
1503                         case UI_BTYPE_TOGGLE:
1504                         case UI_BTYPE_ICON_TOGGLE:
1505                         case UI_BTYPE_CHECKBOX:
1506                                 UI_GET_BUT_VALUE_INIT(but, *value);
1507                                 if (*value != (double)but->hardmin) is_push = true;
1508                                 break;
1509                         case UI_BTYPE_ICON_TOGGLE_N:
1510                         case UI_BTYPE_TOGGLE_N:
1511                         case UI_BTYPE_CHECKBOX_N:
1512                                 UI_GET_BUT_VALUE_INIT(but, *value);
1513                                 if (*value == 0.0) is_push = true;
1514                                 break;
1515                         case UI_BTYPE_ROW:
1516                         case UI_BTYPE_LISTROW:
1517                                 UI_GET_BUT_VALUE_INIT(but, *value);
1518                                 /* support for rna enum buts */
1519                                 if (but->rnaprop && (RNA_property_flag(but->rnaprop) & PROP_ENUM_FLAG)) {
1520                                         if ((int)*value & (int)but->hardmax) is_push = true;
1521                                 }
1522                                 else {
1523                                         if (*value == (double)but->hardmax) is_push = true;
1524                                 }
1525                                 break;
1526                         case UI_BTYPE_TAB:
1527                                 if (but->rnaprop && but->custom_data) {
1528                                         /* uiBut.custom_data points to data this tab represents (e.g. workspace).
1529                                          * uiBut.rnapoin/prop store an active value (e.g. active workspace). */
1530                                         if (RNA_property_type(but->rnaprop) == PROP_POINTER) {
1531                                                 PointerRNA active_ptr = RNA_property_pointer_get(&but->rnapoin, but->rnaprop);
1532                                                 if (active_ptr.data == but->custom_data) {
1533                                                         is_push = true;
1534                                                 }
1535                                         }
1536                                 }
1537                                 break;
1538                         default:
1539                                 is_push = -1;
1540                                 break;
1541                 }
1542         }
1543
1544         return is_push;
1545 }
1546 int ui_but_is_pushed(uiBut *but)
1547 {
1548         double value = UI_BUT_VALUE_UNSET;
1549         return ui_but_is_pushed_ex(but, &value);
1550 }
1551
1552 static void ui_but_update_select_flag(uiBut *but, double *value)
1553 {
1554         switch (ui_but_is_pushed_ex(but, value)) {
1555                 case true:
1556                         but->flag |= UI_SELECT;
1557                         break;
1558                 case false:
1559                         but->flag &= ~UI_SELECT;
1560                         break;
1561         }
1562 }
1563
1564 /* ************************************************ */
1565
1566 void UI_block_lock_set(uiBlock *block, bool val, const char *lockstr)
1567 {
1568         if (val) {
1569                 block->lock = val;
1570                 block->lockstr = lockstr;
1571         }
1572 }
1573
1574 void UI_block_lock_clear(uiBlock *block)
1575 {
1576         block->lock = false;
1577         block->lockstr = NULL;
1578 }
1579
1580 /* *********************** data get/set ***********************
1581  * this either works with the pointed to data, or can work with
1582  * an edit override pointer while dragging for example */
1583
1584 /* Get PointerRNA which will point to a data inside of an evaluated
1585  * ID datablock.
1586  */
1587 static PointerRNA ui_but_evaluated_rnapoin_get(uiBut *but)
1588 {
1589         BLI_assert(but->rnaprop != NULL);
1590         /* TODO(sergey): evil_C sounds.. EVIL! Any clear way to avoid this? */
1591         PointerRNA rnapoin_eval = but->rnapoin;
1592         /* If there is no animation or drivers, it doesn't matter if we read value
1593          * from evaluated datablock or from original one.
1594          *
1595          * Reading from original one is much faster, since we don't need to do any
1596          * PointerRNA remapping or hash lookup.
1597          */
1598         if (BKE_animdata_from_id(but->rnapoin.id.data) == NULL) {
1599                 return rnapoin_eval;
1600         }
1601         /* Same goes for the properties which can not be animated. */
1602         if (!RNA_property_animateable(&but->rnapoin, but->rnaprop)) {
1603                 return rnapoin_eval;
1604         }
1605         Depsgraph *depsgraph = CTX_data_depsgraph(but->block->evil_C);
1606         /* ID pointer we can always remap, they are inside of depsgraph. */
1607         rnapoin_eval.id.data =
1608                 DEG_get_evaluated_id(depsgraph, rnapoin_eval.id.data);
1609         /* Some of ID datablocks do not have their evaluated copy inside
1610          * of dependency graph. If it's such datablock, no need to worry about
1611          * data pointer.
1612          */
1613         if (rnapoin_eval.id.data == but->rnapoin.id.data) {
1614                 return rnapoin_eval;
1615         }
1616         /* For the data pointer it's getting a bit more involved, since it can
1617          * whether be and ID, or can be a property deep inside of ID.
1618          *
1619          * We start from checking if it's an ID, since that is the less involved
1620          * code path, and probably is executed in most of the cases.
1621          */
1622         if (but->rnapoin.data == but->rnapoin.id.data) {
1623                 rnapoin_eval.data = DEG_get_evaluated_id(depsgraph, rnapoin_eval.data);
1624                 return rnapoin_eval;
1625         }
1626         /* We aren't as lucky as we thought we are :(
1627          *
1628          * Since we don't know what the property is, we get it's RNA path
1629          * relative to the original ID, and then we decent down from evaluated
1630          * ID to the same property.
1631          *
1632          * This seems to be most straightforward way to get sub-data pointers
1633          * which can be buried deep inside of ID block.
1634          */
1635         const char *rna_path =
1636                RNA_path_from_ID_to_property(&but->rnapoin, but->rnaprop);
1637         if (rna_path != NULL) {
1638                 PointerRNA id_ptr;
1639                 RNA_id_pointer_create(rnapoin_eval.id.data, &id_ptr);
1640                 if (!RNA_path_resolve_full(&id_ptr,
1641                                            rna_path,
1642                                            &rnapoin_eval,
1643                                            NULL, NULL))
1644                 {
1645                         /* TODO(sergey): Anything to do here to recover? */
1646                 }
1647                 MEM_freeN((void *)rna_path);
1648         }
1649         return rnapoin_eval;
1650 }
1651
1652 /* for buttons pointing to color for example */
1653 void ui_but_v3_get(uiBut *but, float vec[3])
1654 {
1655         PropertyRNA *prop;
1656         int a;
1657
1658         if (but->editvec) {
1659                 copy_v3_v3(vec, but->editvec);
1660         }
1661
1662         if (but->rnaprop) {
1663                 prop = but->rnaprop;
1664
1665                 zero_v3(vec);
1666
1667                 PointerRNA rnapoin_eval = ui_but_evaluated_rnapoin_get(but);
1668
1669                 if (RNA_property_type(prop) == PROP_FLOAT) {
1670                         int tot = RNA_property_array_length(&rnapoin_eval, prop);
1671                         BLI_assert(tot > 0);
1672                         if (tot == 3) {
1673                                 RNA_property_float_get_array(&rnapoin_eval, prop, vec);
1674                         }
1675                         else {
1676                                 tot = min_ii(tot, 3);
1677                                 for (a = 0; a < tot; a++) {
1678                                         vec[a] = RNA_property_float_get_index(&rnapoin_eval, prop, a);
1679                                 }
1680                         }
1681                 }
1682         }
1683         else if (but->pointype == UI_BUT_POIN_CHAR) {
1684                 const char *cp = (char *)but->poin;
1685
1686                 vec[0] = ((float)cp[0]) / 255.0f;
1687                 vec[1] = ((float)cp[1]) / 255.0f;
1688                 vec[2] = ((float)cp[2]) / 255.0f;
1689         }
1690         else if (but->pointype == UI_BUT_POIN_FLOAT) {
1691                 const float *fp = (float *)but->poin;
1692                 copy_v3_v3(vec, fp);
1693         }
1694         else {
1695                 if (but->editvec == NULL) {
1696                         fprintf(stderr, "%s: can't get color, should never happen\n", __func__);
1697                         zero_v3(vec);
1698                 }
1699         }
1700
1701         if (but->type == UI_BTYPE_UNITVEC) {
1702                 normalize_v3(vec);
1703         }
1704 }
1705
1706 /* for buttons pointing to color for example */
1707 void ui_but_v3_set(uiBut *but, const float vec[3])
1708 {
1709         PropertyRNA *prop;
1710
1711         if (but->editvec) {
1712                 copy_v3_v3(but->editvec, vec);
1713         }
1714
1715         if (but->rnaprop) {
1716                 prop = but->rnaprop;
1717
1718                 if (RNA_property_type(prop) == PROP_FLOAT) {
1719                         int tot;
1720                         int a;
1721
1722                         tot = RNA_property_array_length(&but->rnapoin, prop);
1723                         BLI_assert(tot > 0);
1724                         if (tot == 3) {
1725                                 RNA_property_float_set_array(&but->rnapoin, prop, vec);
1726                         }
1727                         else {
1728                                 tot = min_ii(tot, 3);
1729                                 for (a = 0; a < tot; a++) {
1730                                         RNA_property_float_set_index(&but->rnapoin, prop, a, vec[a]);
1731                                 }
1732                         }
1733                 }
1734         }
1735         else if (but->pointype == UI_BUT_POIN_CHAR) {
1736                 char *cp = (char *)but->poin;
1737                 cp[0] = (char)(0.5f + vec[0] * 255.0f);
1738                 cp[1] = (char)(0.5f + vec[1] * 255.0f);
1739                 cp[2] = (char)(0.5f + vec[2] * 255.0f);
1740         }
1741         else if (but->pointype == UI_BUT_POIN_FLOAT) {
1742                 float *fp = (float *)but->poin;
1743                 copy_v3_v3(fp, vec);
1744         }
1745 }
1746
1747 bool ui_but_is_float(const uiBut *but)
1748 {
1749         if (but->pointype == UI_BUT_POIN_FLOAT && but->poin)
1750                 return true;
1751
1752         if (but->rnaprop && RNA_property_type(but->rnaprop) == PROP_FLOAT)
1753                 return true;
1754
1755         return false;
1756 }
1757
1758 bool ui_but_is_bool(const uiBut *but)
1759 {
1760         if (ELEM(but->type, UI_BTYPE_TOGGLE, UI_BTYPE_TOGGLE_N, UI_BTYPE_ICON_TOGGLE, UI_BTYPE_ICON_TOGGLE_N))
1761                 return true;
1762
1763         if (but->rnaprop && RNA_property_type(but->rnaprop) == PROP_BOOLEAN)
1764                 return true;
1765
1766         if ((but->rnaprop && RNA_property_type(but->rnaprop) == PROP_ENUM) && (but->type == UI_BTYPE_ROW))
1767                 return true;
1768
1769         return false;
1770 }
1771
1772
1773 bool ui_but_is_unit(const uiBut *but)
1774 {
1775         UnitSettings *unit = but->block->unit;
1776         const int unit_type = UI_but_unit_type_get(but);
1777
1778         if (unit_type == PROP_UNIT_NONE)
1779                 return false;
1780
1781 #if 1 /* removed so angle buttons get correct snapping */
1782         if (ui_but_is_unit_radians_ex(unit, unit_type))
1783                 return false;
1784 #endif
1785
1786         /* for now disable time unit conversion */
1787         if (unit_type == PROP_UNIT_TIME)
1788                 return false;
1789
1790         if (unit->system == USER_UNIT_NONE) {
1791                 if (unit_type != PROP_UNIT_ROTATION) {
1792                         return false;
1793                 }
1794         }
1795
1796         return true;
1797 }
1798
1799 /**
1800  * Check if this button is similar enough to be grouped with another.
1801  */
1802 bool ui_but_is_compatible(const uiBut *but_a, const uiBut *but_b)
1803 {
1804         if (but_a->type != but_b->type)
1805                 return false;
1806         if (but_a->pointype != but_b->pointype)
1807                 return false;
1808
1809         if (but_a->rnaprop) {
1810                 /* skip 'rnapoin.data', 'rnapoin.id.data'
1811                  * allow different data to have the same props edited at once */
1812                 if (but_a->rnapoin.type != but_b->rnapoin.type)
1813                         return false;
1814                 if (RNA_property_type(but_a->rnaprop) != RNA_property_type(but_b->rnaprop))
1815                         return false;
1816                 if (RNA_property_subtype(but_a->rnaprop) != RNA_property_subtype(but_b->rnaprop))
1817                         return false;
1818         }
1819
1820         return true;
1821 }
1822
1823 bool ui_but_is_rna_valid(uiBut *but)
1824 {
1825         if (but->rnaprop == NULL || RNA_struct_contains_property(&but->rnapoin, but->rnaprop)) {
1826                 return true;
1827         }
1828         else {
1829                 printf("property removed %s: %p\n", but->drawstr, but->rnaprop);
1830                 return false;
1831         }
1832 }
1833
1834 /**
1835  * Checks if the button supports ctrl+mousewheel cycling
1836  */
1837 bool ui_but_supports_cycling(const uiBut *but)
1838 {
1839         return ((ELEM(but->type, UI_BTYPE_ROW, UI_BTYPE_NUM, UI_BTYPE_NUM_SLIDER, UI_BTYPE_LISTBOX)) ||
1840                 (but->type == UI_BTYPE_MENU && ui_but_menu_step_poll(but)) ||
1841                 (but->type == UI_BTYPE_COLOR && but->a1 != -1) ||
1842                 (but->menu_step_func != NULL));
1843 }
1844
1845 double ui_but_value_get(uiBut *but)
1846 {
1847         PropertyRNA *prop;
1848         double value = 0.0;
1849
1850         if (but->editval) { return *(but->editval); }
1851         if (but->poin == NULL && but->rnapoin.data == NULL) return 0.0;
1852
1853         if (but->rnaprop) {
1854                 prop = but->rnaprop;
1855
1856                 BLI_assert(but->rnaindex != -1);
1857
1858                 PointerRNA rnapoin_eval = ui_but_evaluated_rnapoin_get(but);
1859
1860                 switch (RNA_property_type(prop)) {
1861                         case PROP_BOOLEAN:
1862                                 if (RNA_property_array_check(prop))
1863                                         value = RNA_property_boolean_get_index(&rnapoin_eval, prop, but->rnaindex);
1864                                 else
1865                                         value = RNA_property_boolean_get(&rnapoin_eval, prop);
1866                                 break;
1867                         case PROP_INT:
1868                                 if (RNA_property_array_check(prop))
1869                                         value = RNA_property_int_get_index(&rnapoin_eval, prop, but->rnaindex);
1870                                 else
1871                                         value = RNA_property_int_get(&rnapoin_eval, prop);
1872                                 break;
1873                         case PROP_FLOAT:
1874                                 if (RNA_property_array_check(prop))
1875                                         value = RNA_property_float_get_index(&rnapoin_eval, prop, but->rnaindex);
1876                                 else
1877                                         value = RNA_property_float_get(&rnapoin_eval, prop);
1878                                 break;
1879                         case PROP_ENUM:
1880                                 value = RNA_property_enum_get(&rnapoin_eval, prop);
1881                                 break;
1882                         default:
1883                                 value = 0.0;
1884                                 break;
1885                 }
1886         }
1887         else if (but->pointype == UI_BUT_POIN_CHAR) {
1888                 value = *(char *)but->poin;
1889         }
1890         else if (but->pointype == UI_BUT_POIN_SHORT) {
1891                 value = *(short *)but->poin;
1892         }
1893         else if (but->pointype == UI_BUT_POIN_INT) {
1894                 value = *(int *)but->poin;
1895         }
1896         else if (but->pointype == UI_BUT_POIN_FLOAT) {
1897                 value = *(float *)but->poin;
1898         }
1899
1900         return value;
1901 }
1902
1903 void ui_but_value_set(uiBut *but, double value)
1904 {
1905         PropertyRNA *prop;
1906
1907         /* value is a hsv value: convert to rgb */
1908         if (but->rnaprop) {
1909                 prop = but->rnaprop;
1910
1911                 if (RNA_property_editable(&but->rnapoin, prop)) {
1912                         switch (RNA_property_type(prop)) {
1913                                 case PROP_BOOLEAN:
1914                                         if (RNA_property_array_check(prop))
1915                                                 RNA_property_boolean_set_index(&but->rnapoin, prop, but->rnaindex, value);
1916                                         else
1917                                                 RNA_property_boolean_set(&but->rnapoin, prop, value);
1918                                         break;
1919                                 case PROP_INT:
1920                                         if (RNA_property_array_check(prop))
1921                                                 RNA_property_int_set_index(&but->rnapoin, prop, but->rnaindex, (int)value);
1922                                         else
1923                                                 RNA_property_int_set(&but->rnapoin, prop, (int)value);
1924                                         break;
1925                                 case PROP_FLOAT:
1926                                         if (RNA_property_array_check(prop))
1927                                                 RNA_property_float_set_index(&but->rnapoin, prop, but->rnaindex, value);
1928                                         else
1929                                                 RNA_property_float_set(&but->rnapoin, prop, value);
1930                                         break;
1931                                 case PROP_ENUM:
1932                                         if (RNA_property_flag(prop) & PROP_ENUM_FLAG) {
1933                                                 int ivalue = (int)value;
1934                                                 ivalue ^= RNA_property_enum_get(&but->rnapoin, prop); /* toggle for enum/flag buttons */
1935                                                 RNA_property_enum_set(&but->rnapoin, prop, ivalue);
1936                                         }
1937                                         else {
1938                                                 RNA_property_enum_set(&but->rnapoin, prop, value);
1939                                         }
1940                                         break;
1941                                 default:
1942                                         break;
1943                         }
1944                 }
1945
1946                 /* we can't be sure what RNA set functions actually do,
1947                  * so leave this unset */
1948                 value = UI_BUT_VALUE_UNSET;
1949         }
1950         else if (but->pointype == 0) {
1951                 /* pass */
1952         }
1953         else {
1954                 /* first do rounding */
1955                 if (but->pointype == UI_BUT_POIN_CHAR) {
1956                         value = round_db_to_uchar_clamp(value);
1957                 }
1958                 else if (but->pointype == UI_BUT_POIN_SHORT) {
1959                         value = round_db_to_short_clamp(value);
1960                 }
1961                 else if (but->pointype == UI_BUT_POIN_INT) {
1962                         value = round_db_to_int_clamp(value);
1963                 }
1964                 else if (but->pointype == UI_BUT_POIN_FLOAT) {
1965                         float fval = (float)value;
1966                         if (fval >= -0.00001f && fval <= 0.00001f) fval = 0.0f;  /* prevent negative zero */
1967                         value = fval;
1968                 }
1969
1970                 /* then set value with possible edit override */
1971                 if (but->editval)
1972                         value = *but->editval = value;
1973                 else if (but->pointype == UI_BUT_POIN_CHAR)
1974                         value = *((char *)but->poin) = (char)value;
1975                 else if (but->pointype == UI_BUT_POIN_SHORT)
1976                         value = *((short *)but->poin) = (short)value;
1977                 else if (but->pointype == UI_BUT_POIN_INT)
1978                         value = *((int *)but->poin) = (int)value;
1979                 else if (but->pointype == UI_BUT_POIN_FLOAT)
1980                         value = *((float *)but->poin) = (float)value;
1981         }
1982
1983         ui_but_update_select_flag(but, &value);
1984 }
1985
1986 int ui_but_string_get_max_length(uiBut *but)
1987 {
1988         if (ELEM(but->type, UI_BTYPE_TEXT, UI_BTYPE_SEARCH_MENU))
1989                 return but->hardmax;
1990         else
1991                 return UI_MAX_DRAW_STR;
1992 }
1993
1994 uiBut *ui_but_drag_multi_edit_get(uiBut *but)
1995 {
1996         uiBut *but_iter;
1997
1998         BLI_assert(but->flag & UI_BUT_DRAG_MULTI);
1999
2000         for (but_iter = but->block->buttons.first; but_iter; but_iter = but_iter->next) {
2001                 if (but_iter->editstr) {
2002                         break;
2003                 }
2004         }
2005
2006         return but_iter;
2007 }
2008
2009 /** \name Check to show extra icons
2010  *
2011  * Extra icons are shown on the right hand side of buttons.
2012  * This could (should!) definitely become more generic, but for now this is good enough.
2013  * \{ */
2014
2015 static bool ui_but_icon_extra_is_visible_text_clear(const uiBut *but)
2016 {
2017         BLI_assert(but->type == UI_BTYPE_TEXT);
2018         return ((but->flag & UI_BUT_VALUE_CLEAR) && but->drawstr[0]);
2019 }
2020
2021 static bool ui_but_icon_extra_is_visible_search_unlink(const uiBut *but)
2022 {
2023         BLI_assert(ELEM(but->type, UI_BTYPE_SEARCH_MENU, UI_BTYPE_TAB));
2024         return ((but->editstr == NULL) &&
2025                 (but->drawstr[0] != '\0') &&
2026                 (but->flag & UI_BUT_VALUE_CLEAR));
2027 }
2028
2029 static bool ui_but_icon_extra_is_visible_search_eyedropper(uiBut *but)
2030 {
2031         StructRNA *type;
2032         short idcode;
2033
2034         BLI_assert(but->type == UI_BTYPE_SEARCH_MENU && (but->flag & UI_BUT_VALUE_CLEAR));
2035
2036         if (but->rnaprop == NULL) {
2037                 return false;
2038         }
2039
2040         type = RNA_property_pointer_type(&but->rnapoin, but->rnaprop);
2041         idcode = RNA_type_to_ID_code(type);
2042
2043         return ((but->editstr == NULL) &&
2044                 (idcode == ID_OB || OB_DATA_SUPPORT_ID(idcode)));
2045 }
2046
2047 uiButExtraIconType ui_but_icon_extra_get(uiBut *but)
2048 {
2049         switch (but->type) {
2050                 case UI_BTYPE_TEXT:
2051                         if (ui_but_icon_extra_is_visible_text_clear(but)) {
2052                                 return UI_BUT_ICONEXTRA_CLEAR;
2053                         }
2054                         break;
2055                 case UI_BTYPE_SEARCH_MENU:
2056                         if ((but->flag & UI_BUT_VALUE_CLEAR) == 0) {
2057                                 /* pass */
2058                         }
2059                         else if (ui_but_icon_extra_is_visible_search_unlink(but)) {
2060                                 return UI_BUT_ICONEXTRA_CLEAR;
2061                         }
2062                         else if (ui_but_icon_extra_is_visible_search_eyedropper(but)) {
2063                                 return UI_BUT_ICONEXTRA_EYEDROPPER;
2064                         }
2065                         break;
2066                 case UI_BTYPE_TAB:
2067                         if (ui_but_icon_extra_is_visible_search_unlink(but)) {
2068                                 return UI_BUT_ICONEXTRA_CLEAR;
2069                         }
2070                         break;
2071                 default:
2072                         break;
2073         }
2074
2075         return UI_BUT_ICONEXTRA_NONE;
2076 }
2077
2078 /** \} */
2079
2080
2081 static double ui_get_but_scale_unit(uiBut *but, double value)
2082 {
2083         UnitSettings *unit = but->block->unit;
2084         int unit_type = UI_but_unit_type_get(but);
2085
2086         /* Time unit is a bit special, not handled by BKE_scene_unit_scale() for now. */
2087         if (unit_type == PROP_UNIT_TIME) { /* WARNING - using evil_C :| */
2088                 Scene *scene = CTX_data_scene(but->block->evil_C);
2089                 return FRA2TIME(value);
2090         }
2091         else {
2092                 return BKE_scene_unit_scale(unit, RNA_SUBTYPE_UNIT_VALUE(unit_type), value);
2093         }
2094 }
2095
2096 /* str will be overwritten */
2097 void ui_but_convert_to_unit_alt_name(uiBut *but, char *str, size_t maxlen)
2098 {
2099         if (ui_but_is_unit(but)) {
2100                 UnitSettings *unit = but->block->unit;
2101                 int unit_type = UI_but_unit_type_get(but);
2102                 char *orig_str;
2103
2104                 orig_str = BLI_strdup(str);
2105
2106                 bUnit_ToUnitAltName(str, maxlen, orig_str, unit->system, RNA_SUBTYPE_UNIT_VALUE(unit_type));
2107
2108                 MEM_freeN(orig_str);
2109         }
2110 }
2111
2112 /**
2113  * \param float_precision  Override the button precision.
2114  */
2115 static void ui_get_but_string_unit(uiBut *but, char *str, int len_max, double value, bool pad, int float_precision)
2116 {
2117         UnitSettings *unit = but->block->unit;
2118         const bool do_split = (unit->flag & USER_UNIT_OPT_SPLIT) != 0;
2119         int unit_type = UI_but_unit_type_get(but);
2120         int precision;
2121
2122         if (unit->scale_length < 0.0001f) unit->scale_length = 1.0f;  // XXX do_versions
2123
2124         /* Use precision override? */
2125         if (float_precision == -1) {
2126                 /* Sanity checks */
2127                 precision = (int)but->a2;
2128                 if      (precision > UI_PRECISION_FLOAT_MAX) precision = UI_PRECISION_FLOAT_MAX;
2129                 else if (precision == -1)                    precision = 2;
2130         }
2131         else {
2132                 precision = float_precision;
2133         }
2134
2135         bUnit_AsString(str, len_max, ui_get_but_scale_unit(but, value), precision,
2136                        unit->system, RNA_SUBTYPE_UNIT_VALUE(unit_type), do_split, pad);
2137 }
2138
2139 static float ui_get_but_step_unit(uiBut *but, float step_default)
2140 {
2141         int unit_type = RNA_SUBTYPE_UNIT_VALUE(UI_but_unit_type_get(but));
2142         const double step_orig = step_default * UI_PRECISION_FLOAT_SCALE;
2143         /* Scaling up 'step_origg ' here is a bit arbitrary, its just giving better scales from user POV */
2144         const double scale_step = ui_get_but_scale_unit(but, step_orig * 10);
2145         const double step = bUnit_ClosestScalar(scale_step, but->block->unit->system, unit_type);
2146
2147         /* -1 is an error value */
2148         if (step != -1.0) {
2149                 const double scale_unit = ui_get_but_scale_unit(but, 1.0);
2150                 const double step_unit = bUnit_ClosestScalar(scale_unit, but->block->unit->system, unit_type);
2151                 double step_final;
2152
2153                 BLI_assert(step > 0.0);
2154
2155                 step_final = (step / scale_unit) / (double)UI_PRECISION_FLOAT_SCALE;
2156
2157                 if (step == step_unit) {
2158                         /* Logic here is to scale by the original 'step_orig'
2159                          * only when the unit step matches the scaled step.
2160                          *
2161                          * This is needed for units that don't have a wide range of scales (degrees for eg.).
2162                          * Without this we can't select between a single degree, or a 10th of a degree.
2163                          */
2164                         step_final *= step_orig;
2165                 }
2166
2167                 return (float)step_final;
2168         }
2169         else {
2170                 return step_default;
2171         }
2172 }
2173
2174 /**
2175  * \param float_precision  For number buttons the precision to use or -1 to fallback to the button default.
2176  * \param use_exp_float  Use exponent representation of floats when out of reasonable range (outside of 1e3/1e-3).
2177  */
2178 void ui_but_string_get_ex(uiBut *but, char *str, const size_t maxlen, const int float_precision, const bool use_exp_float, bool *r_use_exp_float)
2179 {
2180         if (r_use_exp_float) {
2181                 *r_use_exp_float = false;
2182         }
2183
2184         if (but->rnaprop && ELEM(but->type, UI_BTYPE_TEXT, UI_BTYPE_SEARCH_MENU, UI_BTYPE_TAB)) {
2185                 PropertyType type;
2186                 const char *buf = NULL;
2187                 int buf_len;
2188
2189                 type = RNA_property_type(but->rnaprop);
2190
2191                 if ((but->type == UI_BTYPE_TAB) && (but->custom_data)) {
2192                         StructRNA *ptr_type = RNA_property_pointer_type(&but->rnapoin, but->rnaprop);
2193                         PointerRNA ptr;
2194
2195                         /* uiBut.custom_data points to data this tab represents (e.g. workspace).
2196                          * uiBut.rnapoin/prop store an active value (e.g. active workspace). */
2197                         RNA_pointer_create(but->rnapoin.id.data, ptr_type, but->custom_data, &ptr);
2198                         buf = RNA_struct_name_get_alloc(&ptr, str, maxlen, &buf_len);
2199                 }
2200                 else if (type == PROP_STRING) {
2201                         /* RNA string */
2202                         buf = RNA_property_string_get_alloc(&but->rnapoin, but->rnaprop, str, maxlen, &buf_len);
2203                 }
2204                 else if (type == PROP_ENUM) {
2205                         /* RNA enum */
2206                         int value = RNA_property_enum_get(&but->rnapoin, but->rnaprop);
2207                         if (RNA_property_enum_name(but->block->evil_C, &but->rnapoin, but->rnaprop, value, &buf)) {
2208                                 BLI_strncpy(str, buf, maxlen);
2209                                 buf = str;
2210                         }
2211                 }
2212                 else if (type == PROP_POINTER) {
2213                         /* RNA pointer */
2214                         PointerRNA ptr = RNA_property_pointer_get(&but->rnapoin, but->rnaprop);
2215                         buf = RNA_struct_name_get_alloc(&ptr, str, maxlen, &buf_len);
2216                 }
2217                 else {
2218                         BLI_assert(0);
2219                 }
2220
2221                 if (!buf) {
2222                         str[0] = '\0';
2223                 }
2224                 else if (buf && buf != str) {
2225                         BLI_assert(maxlen <= buf_len + 1);
2226                         /* string was too long, we have to truncate */
2227                         if (ui_but_is_utf8(but)) {
2228                                 BLI_strncpy_utf8(str, buf, maxlen);
2229                         }
2230                         else {
2231                                 BLI_strncpy(str, buf, maxlen);
2232                         }
2233                         MEM_freeN((void *)buf);
2234                 }
2235         }
2236         else if (ELEM(but->type, UI_BTYPE_TEXT, UI_BTYPE_SEARCH_MENU)) {
2237                 /* string */
2238                 BLI_strncpy(str, but->poin, maxlen);
2239                 return;
2240         }
2241         else if (ui_but_anim_expression_get(but, str, maxlen)) {
2242                 /* driver expression */
2243         }
2244         else {
2245                 /* number editing */
2246                 double value;
2247
2248                 value = ui_but_value_get(but);
2249
2250                 if (ui_but_is_float(but)) {
2251                         if (ui_but_is_unit(but)) {
2252                                 ui_get_but_string_unit(but, str, maxlen, value, false, float_precision);
2253                         }
2254                         else {
2255                                 int prec = (float_precision == -1) ? ui_but_calc_float_precision(but, value) : float_precision;
2256                                 if (use_exp_float) {
2257                                         const int int_digits_num = integer_digits_f(value);
2258                                         if (int_digits_num < -6 || int_digits_num > 12) {
2259                                                 BLI_snprintf(str, maxlen, "%.*g", prec, value);
2260                                                 if (r_use_exp_float) {
2261                                                         *r_use_exp_float = true;
2262                                                 }
2263                                         }
2264                                         else {
2265                                                 prec -= int_digits_num;
2266                                                 CLAMP(prec, 0, UI_PRECISION_FLOAT_MAX);
2267                                                 BLI_snprintf(str, maxlen, "%.*f", prec, value);
2268                                         }
2269                                 }
2270                                 else {
2271 #if 0                           /* TODO, but will likely break some stuff, so better after 2.79 release. */
2272                                         prec -= int_digits_num;
2273                                         CLAMP(prec, 0, UI_PRECISION_FLOAT_MAX);
2274 #endif
2275                                         BLI_snprintf(str, maxlen, "%.*f", prec, value);
2276                                 }
2277                         }
2278                 }
2279                 else {
2280                         BLI_snprintf(str, maxlen, "%d", (int)value);
2281                 }
2282         }
2283 }
2284 void ui_but_string_get(uiBut *but, char *str, const size_t maxlen)
2285 {
2286         ui_but_string_get_ex(but, str, maxlen, -1, false, NULL);
2287 }
2288
2289 /**
2290  * A version of #ui_but_string_get_ex for dynamic buffer sizes
2291  * (where #ui_but_string_get_max_length returns 0).
2292  *
2293  * \param r_str_size: size of the returned string (including terminator).
2294  */
2295 char *ui_but_string_get_dynamic(uiBut *but, int *r_str_size)
2296 {
2297         char *str = NULL;
2298         *r_str_size = 1;
2299
2300         if (but->rnaprop && ELEM(but->type, UI_BTYPE_TEXT, UI_BTYPE_SEARCH_MENU)) {
2301                 PropertyType type;
2302
2303                 type = RNA_property_type(but->rnaprop);
2304
2305                 if (type == PROP_STRING) {
2306                         /* RNA string */
2307                         str = RNA_property_string_get_alloc(&but->rnapoin, but->rnaprop, NULL, 0, r_str_size);
2308                         (*r_str_size) += 1;
2309                 }
2310                 else if (type == PROP_ENUM) {
2311                         /* RNA enum */
2312                         int value = RNA_property_enum_get(&but->rnapoin, but->rnaprop);
2313                         const char *value_id;
2314                         if (!RNA_property_enum_name(but->block->evil_C, &but->rnapoin, but->rnaprop, value, &value_id)) {
2315                                 value_id = "";
2316                         }
2317
2318                         *r_str_size = strlen(value_id) + 1;
2319                         str = BLI_strdupn(value_id, *r_str_size);
2320                 }
2321                 else if (type == PROP_POINTER) {
2322                         /* RNA pointer */
2323                         PointerRNA ptr = RNA_property_pointer_get(&but->rnapoin, but->rnaprop);
2324                         str = RNA_struct_name_get_alloc(&ptr, NULL, 0, r_str_size);
2325                         (*r_str_size) += 1;
2326                 }
2327                 else {
2328                         BLI_assert(0);
2329                 }
2330         }
2331         else {
2332                 BLI_assert(0);
2333         }
2334
2335         if (UNLIKELY(str == NULL)) {
2336                 /* should never happen, paranoid check */
2337                 *r_str_size = 1;
2338                 str = BLI_strdup("");
2339                 BLI_assert(0);
2340
2341         }
2342
2343         return str;
2344 }
2345
2346 #ifdef WITH_PYTHON
2347
2348 static bool ui_set_but_string_eval_num_unit(bContext *C, uiBut *but, const char *str, double *r_value)
2349 {
2350         char str_unit_convert[256];
2351         const int unit_type = UI_but_unit_type_get(but);
2352
2353         BLI_strncpy(str_unit_convert, str, sizeof(str_unit_convert));
2354
2355         /* ugly, use the draw string to get the value,
2356          * this could cause problems if it includes some text which resolves to a unit */
2357         bUnit_ReplaceString(str_unit_convert, sizeof(str_unit_convert), but->drawstr,
2358                             ui_get_but_scale_unit(but, 1.0), but->block->unit->system, RNA_SUBTYPE_UNIT_VALUE(unit_type));
2359
2360         return BPY_execute_string_as_number(C, str_unit_convert, true, r_value);
2361 }
2362
2363 #endif /* WITH_PYTHON */
2364
2365
2366 bool ui_but_string_set_eval_num(bContext *C, uiBut *but, const char *str, double *r_value)
2367 {
2368         bool ok = false;
2369
2370 #ifdef WITH_PYTHON
2371
2372         if (str[0] != '\0') {
2373                 bool is_unit_but = (ui_but_is_float(but) && ui_but_is_unit(but));
2374                 /* only enable verbose if we won't run again with units */
2375                 if (BPY_execute_string_as_number(C, str, is_unit_but == false, r_value)) {
2376                         /* if the value parsed ok without unit conversion this button may still need a unit multiplier */
2377                         if (is_unit_but) {
2378                                 char str_new[128];
2379
2380                                 BLI_snprintf(str_new, sizeof(str_new), "%f", *r_value);
2381                                 ok = ui_set_but_string_eval_num_unit(C, but, str_new, r_value);
2382                         }
2383                         else {
2384                                 ok = true; /* parse normal string via py (no unit conversion needed) */
2385                         }
2386                 }
2387                 else if (is_unit_but) {
2388                         /* parse failed, this is a unit but so run replacements and parse again */
2389                         ok = ui_set_but_string_eval_num_unit(C, but, str, r_value);
2390                 }
2391         }
2392
2393 #else /* WITH_PYTHON */
2394
2395         *r_value = atof(str);
2396         ok = true;
2397
2398         UNUSED_VARS(C, but);
2399
2400 #endif /* WITH_PYTHON */
2401
2402         return ok;
2403 }
2404
2405 /* just the assignment/free part */
2406 static void ui_but_string_set_internal(uiBut *but, const char *str, size_t str_len)
2407 {
2408         BLI_assert(str_len == strlen(str));
2409         BLI_assert(but->str == NULL);
2410         str_len += 1;
2411
2412         if (str_len > UI_MAX_NAME_STR) {
2413                 but->str = MEM_mallocN(str_len, "ui_def_but str");
2414         }
2415         else {
2416                 but->str = but->strdata;
2417         }
2418         memcpy(but->str, str, str_len);
2419 }
2420
2421 static void ui_but_string_free_internal(uiBut *but)
2422 {
2423         if (but->str) {
2424                 if (but->str != but->strdata) {
2425                         MEM_freeN(but->str);
2426                 }
2427                 /* must call 'ui_but_string_set_internal' after */
2428                 but->str = NULL;
2429         }
2430 }
2431
2432 bool ui_but_string_set(bContext *C, uiBut *but, const char *str)
2433 {
2434         if (but->rnaprop && but->rnapoin.data && ELEM(but->type, UI_BTYPE_TEXT, UI_BTYPE_SEARCH_MENU)) {
2435                 if (RNA_property_editable(&but->rnapoin, but->rnaprop)) {
2436                         PropertyType type;
2437
2438                         type = RNA_property_type(but->rnaprop);
2439
2440                         if (type == PROP_STRING) {
2441                                 /* RNA string */
2442                                 RNA_property_string_set(&but->rnapoin, but->rnaprop, str);
2443                                 return true;
2444                         }
2445                         else if (type == PROP_POINTER) {
2446                                 if (str[0] == '\0') {
2447                                         RNA_property_pointer_set(&but->rnapoin, but->rnaprop, PointerRNA_NULL);
2448                                         return true;
2449                                 }
2450                                 else {
2451                                         /* RNA pointer */
2452                                         PointerRNA rptr;
2453                                         PointerRNA ptr = but->rnasearchpoin;
2454                                         PropertyRNA *prop = but->rnasearchprop;
2455
2456                                         if (prop && RNA_property_collection_lookup_string(&ptr, prop, str, &rptr))
2457                                                 RNA_property_pointer_set(&but->rnapoin, but->rnaprop, rptr);
2458
2459                                         return true;
2460                                 }
2461
2462                                 return false;
2463                         }
2464                         else if (type == PROP_ENUM) {
2465                                 int value;
2466                                 if (RNA_property_enum_value(but->block->evil_C, &but->rnapoin, but->rnaprop, str, &value)) {
2467                                         RNA_property_enum_set(&but->rnapoin, but->rnaprop, value);
2468                                         return true;
2469                                 }
2470                                 return false;
2471                         }
2472                         else {
2473                                 BLI_assert(0);
2474                         }
2475                 }
2476         }
2477         else if (but->type == UI_BTYPE_TAB) {
2478                 if (but->rnaprop && but->custom_data) {
2479                         StructRNA *ptr_type = RNA_property_pointer_type(&but->rnapoin, but->rnaprop);
2480                         PointerRNA ptr;
2481                         PropertyRNA *prop;
2482
2483                         /* uiBut.custom_data points to data this tab represents (e.g. workspace).
2484                          * uiBut.rnapoin/prop store an active value (e.g. active workspace). */
2485                         RNA_pointer_create(but->rnapoin.id.data, ptr_type, but->custom_data, &ptr);
2486                         prop = RNA_struct_name_property(ptr_type);
2487                         if (RNA_property_editable(&ptr, prop)) {
2488                                 RNA_property_string_set(&ptr, prop, str);
2489                         }
2490                 }
2491         }
2492         else if (but->type == UI_BTYPE_TEXT) {
2493                 /* string */
2494                 if (!but->poin || (str[0] == '\0')) {
2495                         str = "";
2496                 }
2497                 else if (ui_but_is_utf8(but)) {
2498                         BLI_strncpy_utf8(but->poin, str, but->hardmax);
2499                 }
2500                 else {
2501                         BLI_strncpy(but->poin, str, but->hardmax);
2502                 }
2503
2504                 return true;
2505         }
2506         else if (but->type == UI_BTYPE_SEARCH_MENU) {
2507                 /* string */
2508                 BLI_strncpy(but->poin, str, but->hardmax);
2509                 return true;
2510         }
2511         else if (ui_but_anim_expression_set(but, str)) {
2512                 /* driver expression */
2513                 return true;
2514         }
2515         else if (str[0] == '#') {
2516                 /* shortcut to create new driver expression (versus immediate Py-execution) */
2517                 return ui_but_anim_expression_create(but, str + 1);
2518         }
2519         else {
2520                 /* number editing */
2521                 double value;
2522
2523                 if (ui_but_string_set_eval_num(C, but, str, &value) == false) {
2524                         WM_report_banner_show();
2525                         return false;
2526                 }
2527
2528                 if (!ui_but_is_float(but)) {
2529                         value = floor(value + 0.5);
2530                 }
2531
2532                 /* not that we use hard limits here */
2533                 if (value < (double)but->hardmin) value = but->hardmin;
2534                 if (value > (double)but->hardmax) value = but->hardmax;
2535
2536                 ui_but_value_set(but, value);
2537                 return true;
2538         }
2539
2540         return false;
2541 }
2542
2543 void ui_but_default_set(bContext *C, const bool all, const bool use_afterfunc)
2544 {
2545         wmOperatorType *ot = WM_operatortype_find("UI_OT_reset_default_button", true);
2546
2547         if (use_afterfunc) {
2548                 PointerRNA *ptr;
2549                 ptr = ui_handle_afterfunc_add_operator(ot, WM_OP_EXEC_DEFAULT, true);
2550                 RNA_boolean_set(ptr, "all", all);
2551         }
2552         else {
2553                 PointerRNA ptr;
2554                 WM_operator_properties_create_ptr(&ptr, ot);
2555                 RNA_boolean_set(&ptr, "all", all);
2556                 WM_operator_name_call_ptr(C, ot, WM_OP_EXEC_DEFAULT, &ptr);
2557                 WM_operator_properties_free(&ptr);
2558         }
2559 }
2560
2561 static double soft_range_round_up(double value, double max)
2562 {
2563         /* round up to .., 0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50, ..
2564          * checking for 0.0 prevents floating point exceptions */
2565         double newmax = (value != 0.0) ? pow(10.0, ceil(log(value) / M_LN10)) : 0.0;
2566
2567         if (newmax * 0.2 >= max && newmax * 0.2 >= value)
2568                 return newmax * 0.2;
2569         else if (newmax * 0.5 >= max && newmax * 0.5 >= value)
2570                 return newmax * 0.5;
2571         else
2572                 return newmax;
2573 }
2574
2575 static double soft_range_round_down(double value, double max)
2576 {
2577         /* round down to .., 0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50, ..
2578          * checking for 0.0 prevents floating point exceptions */
2579         double newmax = (value != 0.0) ? pow(10.0, floor(log(value) / M_LN10)) : 0.0;
2580
2581         if (newmax * 5.0 <= max && newmax * 5.0 <= value)
2582                 return newmax * 5.0;
2583         else if (newmax * 2.0 <= max && newmax * 2.0 <= value)
2584                 return newmax * 2.0;
2585         else
2586                 return newmax;
2587 }
2588
2589 /* note: this could be split up into functions which handle arrays and not */
2590 static void ui_set_but_soft_range(uiBut *but)
2591 {
2592         /* ideally we would not limit this but practically, its more than
2593          * enough worst case is very long vectors wont use a smart soft-range
2594          * which isn't so bad. */
2595
2596         if (but->rnaprop) {
2597                 const PropertyType type = RNA_property_type(but->rnaprop);
2598                 double softmin, softmax /*, step, precision*/;
2599                 double value_min;
2600                 double value_max;
2601
2602                 /* clamp button range to something reasonable in case
2603                  * we get -inf/inf from RNA properties */
2604                 if (type == PROP_INT) {
2605                         const bool is_array = RNA_property_array_check(but->rnaprop);
2606                         int imin, imax, istep;
2607
2608                         RNA_property_int_ui_range(&but->rnapoin, but->rnaprop, &imin, &imax, &istep);
2609                         softmin = (imin == INT_MIN) ? -1e4 : imin;
2610                         softmax = (imin == INT_MAX) ? 1e4 : imax;
2611                         /*step = istep;*/ /*UNUSED*/
2612                         /*precision = 1;*/ /*UNUSED*/
2613
2614                         if (is_array) {
2615                                 int value_range[2];
2616                                 RNA_property_int_get_array_range(&but->rnapoin, but->rnaprop, value_range);
2617                                 value_min = (double)value_range[0];
2618                                 value_max = (double)value_range[1];
2619                         }
2620                         else {
2621                                 value_min = value_max = (double)RNA_property_int_get(&but->rnapoin, but->rnaprop);
2622                         }
2623                 }
2624                 else if (type == PROP_FLOAT) {
2625                         const bool is_array = RNA_property_array_check(but->rnaprop);
2626                         float fmin, fmax, fstep, fprecision;
2627
2628                         RNA_property_float_ui_range(&but->rnapoin, but->rnaprop, &fmin, &fmax, &fstep, &fprecision);
2629                         softmin = (fmin == -FLT_MAX) ? (float)-1e4 : fmin;
2630                         softmax = (fmax == FLT_MAX) ? (float)1e4 : fmax;
2631                         /*step = fstep;*/ /*UNUSED*/
2632                         /*precision = fprecision;*/ /*UNUSED*/
2633
2634                         if (is_array) {
2635                                 float value_range[2];
2636                                 RNA_property_float_get_array_range(&but->rnapoin, but->rnaprop, value_range);
2637                                 value_min = (double)value_range[0];
2638                                 value_max = (double)value_range[1];
2639                         }
2640                         else {
2641                                 value_min = value_max = (double)RNA_property_float_get(&but->rnapoin, but->rnaprop);
2642                         }
2643                 }
2644                 else {
2645                         return;
2646                 }
2647
2648                 /* if the value goes out of the soft/max range, adapt the range */
2649                 if (value_min + 1e-10 < softmin) {
2650                         if (value_min < 0.0)
2651                                 softmin = -soft_range_round_up(-value_min, -softmin);
2652                         else
2653                                 softmin = soft_range_round_down(value_min, softmin);
2654
2655                         if (softmin < (double)but->hardmin)
2656                                 softmin = (double)but->hardmin;
2657                 }
2658                 if (value_max - 1e-10 > softmax) {
2659                         if (value_max < 0.0)
2660                                 softmax = -soft_range_round_down(-value_max, -softmax);
2661                         else
2662                                 softmax = soft_range_round_up(value_max, softmax);
2663
2664                         if (softmax > (double)but->hardmax)
2665                                 softmax = but->hardmax;
2666                 }
2667
2668                 but->softmin = softmin;
2669                 but->softmax = softmax;
2670         }
2671         else if (but->poin && (but->pointype & UI_BUT_POIN_TYPES)) {
2672                 float value = ui_but_value_get(but);
2673                 if (isfinite(value)) {
2674                         CLAMP(value, but->hardmin, but->hardmax);
2675                         but->softmin = min_ff(but->softmin, value);
2676                         but->softmax = max_ff(but->softmax, value);
2677                 }
2678         }
2679         else {
2680                 BLI_assert(0);
2681         }
2682 }
2683
2684 /* ******************* Free ********************/
2685
2686 /* can be called with C==NULL */
2687 static void ui_but_free(const bContext *C, uiBut *but)
2688 {
2689         if (but->opptr) {
2690                 WM_operator_properties_free(but->opptr);
2691                 MEM_freeN(but->opptr);
2692         }
2693
2694         if (but->func_argN) {
2695                 MEM_freeN(but->func_argN);
2696         }
2697
2698         if (but->tip_argN) {
2699                 MEM_freeN(but->tip_argN);
2700         }
2701
2702         if (but->hold_argN) {
2703                 MEM_freeN(but->hold_argN);
2704         }
2705
2706         if (!but->editstr && but->free_search_arg) {
2707                 MEM_SAFE_FREE(but->search_arg);
2708         }
2709
2710         if (but->active) {
2711                 /* XXX solve later, buttons should be free-able without context ideally,
2712                  * however they may have open tooltips or popup windows, which need to
2713                  * be closed using a context pointer */
2714                 if (C) {
2715                         ui_but_active_free(C, but);
2716                 }
2717                 else {
2718                         if (but->active) {
2719                                 MEM_freeN(but->active);
2720                         }
2721                 }
2722         }
2723         if (but->str && but->str != but->strdata) {
2724                 MEM_freeN(but->str);
2725         }
2726
2727         if ((but->type == UI_BTYPE_IMAGE) && but->poin) {
2728                 IMB_freeImBuf((struct ImBuf *)but->poin);
2729         }
2730
2731         if (but->dragpoin && (but->dragflag & UI_BUT_DRAGPOIN_FREE)) {
2732                 MEM_freeN(but->dragpoin);
2733         }
2734
2735         BLI_assert(UI_butstore_is_registered(but->block, but) == false);
2736
2737         MEM_freeN(but);
2738 }
2739
2740 /* can be called with C==NULL */
2741 void UI_block_free(const bContext *C, uiBlock *block)
2742 {
2743         uiBut *but;
2744
2745         UI_butstore_clear(block);
2746
2747         while ((but = BLI_pophead(&block->buttons))) {
2748                 ui_but_free(C, but);
2749         }
2750
2751         if (block->unit) {
2752                 MEM_freeN(block->unit);
2753         }
2754
2755         if (block->func_argN) {
2756                 MEM_freeN(block->func_argN);
2757         }
2758
2759         CTX_store_free_list(&block->contexts);
2760
2761         BLI_freelistN(&block->saferct);
2762         BLI_freelistN(&block->color_pickers.list);
2763
2764         MEM_freeN(block);
2765 }
2766
2767 void UI_blocklist_update_window_matrix(const bContext *C, const ListBase *lb)
2768 {
2769         ARegion *region = CTX_wm_region(C);
2770         wmWindow *window = CTX_wm_window(C);
2771
2772         for (uiBlock *block = lb->first; block; block = block->next) {
2773                 if (block->active) {
2774                         ui_update_window_matrix(window, region, block);
2775                 }
2776         }
2777 }
2778
2779 void UI_blocklist_draw(const bContext *C, const ListBase *lb)
2780 {
2781         for (uiBlock *block = lb->first; block; block = block->next) {
2782                 if (block->active) {
2783                         UI_block_draw(C, block);
2784                 }
2785         }
2786 }
2787
2788 /* can be called with C==NULL */
2789 void UI_blocklist_free(const bContext *C, ListBase *lb)
2790 {
2791         uiBlock *block;
2792
2793         while ((block = BLI_pophead(lb))) {
2794                 UI_block_free(C, block);
2795         }
2796 }
2797
2798 void UI_blocklist_free_inactive(const bContext *C, ListBase *lb)
2799 {
2800         uiBlock *block, *nextblock;
2801
2802         for (block = lb->first; block; block = nextblock) {
2803                 nextblock = block->next;
2804
2805                 if (!block->handle) {
2806                         if (!block->active) {
2807                                 BLI_remlink(lb, block);
2808                                 UI_block_free(C, block);
2809                         }
2810                         else
2811                                 block->active = 0;
2812                 }
2813         }
2814 }
2815
2816 void UI_block_region_set(uiBlock *block, ARegion *region)
2817 {
2818         ListBase *lb = &region->uiblocks;
2819         uiBlock *oldblock = NULL;
2820
2821         /* each listbase only has one block with this name, free block
2822          * if is already there so it can be rebuilt from scratch */
2823         if (lb) {
2824                 oldblock = BLI_findstring(lb, block->name, offsetof(uiBlock, name));
2825
2826                 if (oldblock) {
2827                         oldblock->active = 0;
2828                         oldblock->panel = NULL;
2829                         oldblock->handle = NULL;
2830                 }
2831
2832                 /* at the beginning of the list! for dynamical menus/blocks */
2833                 BLI_addhead(lb, block);
2834         }
2835
2836         block->oldblock = oldblock;
2837 }
2838
2839 uiBlock *UI_block_begin(const bContext *C, ARegion *region, const char *name, short dt)
2840 {
2841         uiBlock *block;
2842         wmWindow *window;
2843         Scene *scn;
2844
2845         window = CTX_wm_window(C);
2846         scn = CTX_data_scene(C);
2847
2848         block = MEM_callocN(sizeof(uiBlock), "uiBlock");
2849         block->active = 1;
2850         block->dt = dt;
2851         block->evil_C = (void *)C;  /* XXX */
2852
2853         if (scn) {
2854                 block->color_profile = true;
2855
2856                 /* store display device name, don't lookup for transformations yet
2857                  * block could be used for non-color displays where looking up for transformation
2858                  * would slow down redraw, so only lookup for actual transform when it's indeed
2859                  * needed
2860                  */
2861                 BLI_strncpy(block->display_device, scn->display_settings.display_device, sizeof(block->display_device));
2862
2863                 /* copy to avoid crash when scene gets deleted with ui still open */
2864                 block->unit = MEM_mallocN(sizeof(scn->unit), "UI UnitSettings");
2865                 memcpy(block->unit, &scn->unit, sizeof(scn->unit));
2866         }
2867
2868         BLI_strncpy(block->name, name, sizeof(block->name));
2869
2870         if (region)
2871                 UI_block_region_set(block, region);
2872
2873         /* Set window matrix and aspect for region and OpenGL state. */
2874         ui_update_window_matrix(window, region, block);
2875
2876         /* Tag as popup menu if not created within a region. */
2877         if (!(region && region->visible)) {
2878                 block->auto_open = true;
2879                 block->flag |= UI_BLOCK_LOOP;
2880         }
2881
2882         return block;
2883 }
2884
2885 void UI_block_emboss_set(uiBlock *block, char dt)
2886 {
2887         block->dt = dt;
2888 }
2889
2890 /**
2891  * \param but: Button to update.
2892  * \param validate: When set, this function may change the button value.
2893  * Otherwise treat the button value as read-only.
2894  */
2895 void ui_but_update_ex(uiBut *but, const bool validate)
2896 {
2897         /* if something changed in the button */
2898         double value = UI_BUT_VALUE_UNSET;
2899 //      float okwidth; // UNUSED
2900
2901         ui_but_update_select_flag(but, &value);
2902
2903         /* only update soft range while not editing */
2904         if (!(but->editval || but->editstr || but->editvec)) {
2905                 if ((but->rnaprop != NULL) ||
2906                     (but->poin && (but->pointype & UI_BUT_POIN_TYPES)))
2907                 {
2908                         ui_set_but_soft_range(but);
2909                 }
2910         }
2911
2912         /* test for min and max, icon sliders, etc */
2913         switch (but->type) {
2914                 case UI_BTYPE_NUM:
2915                 case UI_BTYPE_SCROLL:
2916                 case UI_BTYPE_NUM_SLIDER:
2917                         if (validate) {
2918                                 UI_GET_BUT_VALUE_INIT(but, value);
2919                                 if      (value < (double)but->hardmin) {
2920                                         ui_but_value_set(but, but->hardmin);
2921                                 }
2922                                 else if (value > (double)but->hardmax) {
2923                                         ui_but_value_set(but, but->hardmax);
2924                                 }
2925
2926                                 /* max must never be smaller than min! Both being equal is allowed though */
2927                                 BLI_assert(but->softmin <= but->softmax &&
2928                                            but->hardmin <= but->hardmax);
2929                         }
2930                         break;
2931
2932                 case UI_BTYPE_ICON_TOGGLE:
2933                 case UI_BTYPE_ICON_TOGGLE_N:
2934                         if (!but->rnaprop || (RNA_property_flag(but->rnaprop) & PROP_ICONS_CONSECUTIVE)) {
2935                                 if (but->flag & UI_SELECT) but->iconadd = 1;
2936                                 else but->iconadd = 0;
2937                         }
2938                         break;
2939
2940                         /* quiet warnings for unhandled types */
2941                 default:
2942                         break;
2943         }
2944
2945
2946         /* safety is 4 to enable small number buttons (like 'users') */
2947         // okwidth = -4 + (BLI_rcti_size_x(&but->rect)); // UNUSED
2948
2949         /* name: */
2950         switch (but->type) {
2951
2952                 case UI_BTYPE_MENU:
2953                         if (BLI_rctf_size_x(&but->rect) >= (UI_UNIT_X * 2)) {
2954                                 /* only needed for menus in popup blocks that don't recreate buttons on redraw */
2955                                 if (but->block->flag & UI_BLOCK_LOOP) {
2956                                         if (but->rnaprop && (RNA_property_type(but->rnaprop) == PROP_ENUM)) {
2957                                                 int value_enum = RNA_property_enum_get(&but->rnapoin, but->rnaprop);
2958
2959                                                 EnumPropertyItem item;
2960                                                 if (RNA_property_enum_item_from_value_gettexted(
2961                                                         but->block->evil_C,
2962                                                         &but->rnapoin, but->rnaprop, value_enum, &item))
2963                                                 {
2964                                                         size_t slen = strlen(item.name);
2965                                                         ui_but_string_free_internal(but);
2966                                                         ui_but_string_set_internal(but, item.name, slen);
2967                                                         but->icon = item.icon;
2968                                                 }
2969                                         }
2970                                 }
2971                                 BLI_strncpy(but->drawstr, but->str, sizeof(but->drawstr));
2972                         }
2973                         break;
2974
2975                 case UI_BTYPE_NUM:
2976                 case UI_BTYPE_NUM_SLIDER:
2977
2978                         if (!but->editstr) {
2979                                 const char *drawstr_suffix = NULL;
2980                                 size_t slen;
2981
2982                                 UI_GET_BUT_VALUE_INIT(but, value);
2983
2984                                 slen = BLI_strncpy_rlen(but->drawstr, but->str, sizeof(but->drawstr));
2985
2986                                 if (ui_but_is_float(but)) {
2987                                         if (value == (double) FLT_MAX) {
2988                                                 slen += BLI_strncpy_rlen(but->drawstr + slen, "inf", sizeof(but->drawstr) - slen);
2989                                         }
2990                                         else if (value == (double) -FLT_MAX) {
2991                                                 slen += BLI_strncpy_rlen(but->drawstr + slen, "-inf", sizeof(but->drawstr) - slen);
2992                                         }
2993                                         /* support length type buttons */
2994                                         else if (ui_but_is_unit(but)) {
2995                                                 char new_str[sizeof(but->drawstr)];
2996                                                 ui_get_but_string_unit(but, new_str, sizeof(new_str), value, true, -1);
2997                                                 slen += BLI_strncpy_rlen(but->drawstr + slen, new_str, sizeof(but->drawstr) - slen);
2998                                         }
2999                                         else {
3000                                                 const int prec = ui_but_calc_float_precision(but, value);
3001                                                 slen += BLI_snprintf_rlen(but->drawstr + slen, sizeof(but->drawstr) - slen, "%.*f", prec, value);
3002                                         }
3003                                 }
3004                                 else {
3005                                         slen += BLI_snprintf_rlen(but->drawstr + slen, sizeof(but->drawstr) - slen, "%d", (int)value);
3006                                 }
3007
3008                                 if (but->rnaprop) {
3009                                         PropertySubType pstype = RNA_property_subtype(but->rnaprop);
3010
3011                                         if (pstype == PROP_PERCENTAGE) {
3012                                                 drawstr_suffix = "%";
3013                                         }
3014                                         else if (pstype == PROP_PIXEL) {
3015                                                 drawstr_suffix = " px";
3016                                         }
3017                                 }
3018
3019                                 if (drawstr_suffix) {
3020                                         BLI_strncpy(but->drawstr + slen, drawstr_suffix, sizeof(but->drawstr) - slen);
3021                                 }
3022
3023                         }
3024                         break;
3025
3026                 case UI_BTYPE_LABEL:
3027                         if (ui_but_is_float(but)) {
3028                                 int prec;
3029                                 UI_GET_BUT_VALUE_INIT(but, value);
3030                                 prec = ui_but_calc_float_precision(but, value);
3031                                 BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s%.*f", but->str, prec, value);
3032                         }
3033                         else {
3034                                 BLI_strncpy(but->drawstr, but->str, UI_MAX_DRAW_STR);
3035                         }
3036
3037                         break;
3038
3039                 case UI_BTYPE_TEXT:
3040                 case UI_BTYPE_SEARCH_MENU:
3041                 case UI_BTYPE_TAB:
3042                         if (!but->editstr) {
3043                                 char str[UI_MAX_DRAW_STR];
3044
3045                                 ui_but_string_get(but, str, UI_MAX_DRAW_STR);
3046                                 BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s%s", but->str, str);
3047                         }
3048                         break;
3049
3050                 case UI_BTYPE_KEY_EVENT:
3051                 {
3052                         const char *str;
3053                         if (but->flag & UI_SELECT) {
3054                                 str = "Press a key";
3055                         }
3056                         else {
3057                                 UI_GET_BUT_VALUE_INIT(but, value);
3058                                 str = WM_key_event_string((short)value, false);
3059                         }
3060                         BLI_snprintf(but->drawstr, UI_MAX_DRAW_STR, "%s%s", but->str, str);
3061                         break;
3062                 }
3063                 case UI_BTYPE_HOTKEY_EVENT:
3064                         if (but->flag & UI_SELECT) {
3065
3066                                 if (but->modifier_key) {
3067                                         char *str = but->drawstr;
3068                                         but->drawstr[0] = '\0';
3069
3070                                         if (but->modifier_key & KM_SHIFT)
3071                                                 str += BLI_strcpy_rlen(str, "Shift ");
3072                                         if (but->modifier_key & KM_CTRL)
3073                                                 str += BLI_strcpy_rlen(str, "Ctrl ");
3074                                         if (but->modifier_key & KM_ALT)
3075                                                 str += BLI_strcpy_rlen(str, "Alt ");
3076                                         if (but->modifier_key & KM_OSKEY)
3077                                                 str += BLI_strcpy_rlen(str, "Cmd ");
3078
3079                                         (void)str; /* UNUSED */
3080                                 }
3081                                 else {
3082                                         BLI_strncpy(but->drawstr, "Press a key", UI_MAX_DRAW_STR);
3083                                 }
3084                         }
3085                         else
3086                                 BLI_strncpy(but->drawstr, but->str, UI_MAX_DRAW_STR);
3087
3088                         break;
3089
3090                 case UI_BTYPE_HSVCUBE:
3091                 case UI_BTYPE_HSVCIRCLE:
3092                         break;
3093                 default:
3094                         BLI_strncpy(but->drawstr, but->str, UI_MAX_DRAW_STR);
3095                         break;
3096
3097         }
3098
3099         /* if we are doing text editing, this will override the drawstr */
3100         if (but->editstr)
3101                 but->drawstr[0] = '\0';
3102
3103         /* text clipping moved to widget drawing code itself */
3104 }
3105
3106 void ui_but_update(uiBut *but)
3107 {
3108         ui_but_update_ex(but, false);
3109 }
3110
3111 void ui_but_update_edited(uiBut *but)
3112 {