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