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