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