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