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