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