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 = round_db_to_uchar_clamp(value);
1940                 }
1941                 else if (but->pointype == UI_BUT_POIN_SHORT) {
1942                         value = round_db_to_short_clamp(value);
1943                 }
1944                 else if (but->pointype == UI_BUT_POIN_INT) {
1945                         value = round_db_to_int_clamp(value);
1946                 }
1947                 else if (but->pointype == UI_BUT_POIN_FLOAT) {
1948                         float fval = (float)value;
1949                         if (fval >= -0.00001f && fval <= 0.00001f) fval = 0.0f;  /* prevent negative zero */
1950                         value = fval;
1951                 }
1952                 
1953                 /* then set value with possible edit override */
1954                 if (but->editval)
1955                         value = *but->editval = value;
1956                 else if (but->pointype == UI_BUT_POIN_CHAR)
1957                         value = *((char *)but->poin) = (char)value;
1958                 else if (but->pointype == UI_BUT_POIN_SHORT)
1959                         value = *((short *)but->poin) = (short)value;
1960                 else if (but->pointype == UI_BUT_POIN_INT)
1961                         value = *((int *)but->poin) = (int)value;
1962                 else if (but->pointype == UI_BUT_POIN_FLOAT)
1963                         value = *((float *)but->poin) = (float)value;
1964         }
1965
1966         ui_but_update_select_flag(but, &value);
1967 }
1968
1969 int ui_but_string_get_max_length(uiBut *but)
1970 {
1971         if (ELEM(but->type, UI_BTYPE_TEXT, UI_BTYPE_SEARCH_MENU))
1972                 return but->hardmax;
1973         else
1974                 return UI_MAX_DRAW_STR;
1975 }
1976
1977 uiBut *ui_but_drag_multi_edit_get(uiBut *but)
1978 {
1979         uiBut *but_iter;
1980
1981         BLI_assert(but->flag & UI_BUT_DRAG_MULTI);
1982
1983         for (but_iter = but->block->buttons.first; but_iter; but_iter = but_iter->next) {
1984                 if (but_iter->editstr) {
1985                         break;
1986                 }
1987         }
1988
1989         return but_iter;
1990 }
1991
1992 /** \name Check to show extra icons
1993  *
1994  * Extra icons are shown on the right hand side of buttons.
1995  * This could (should!) definitely become more generic, but for now this is good enough.
1996  * \{ */
1997
1998 static bool ui_but_icon_extra_is_visible_text_clear(const uiBut *but)
1999 {
2000         BLI_assert(but->type == UI_BTYPE_TEXT);
2001         return ((but->flag & UI_BUT_VALUE_CLEAR) && but->drawstr[0]);
2002 }
2003
2004 static bool ui_but_icon_extra_is_visible_search_unlink(const uiBut *but)
2005 {
2006         BLI_assert(but->type == UI_BTYPE_SEARCH_MENU);
2007         return ((but->editstr == NULL) &&
2008                 (but->drawstr[0] != '\0') &&
2009                 (but->flag & UI_BUT_VALUE_CLEAR));
2010 }
2011
2012 static bool ui_but_icon_extra_is_visible_search_eyedropper(uiBut *but)
2013 {
2014         StructRNA *type;
2015         short idcode;
2016
2017         BLI_assert(but->type == UI_BTYPE_SEARCH_MENU && (but->flag & UI_BUT_VALUE_CLEAR));
2018
2019         if (but->rnaprop == NULL) {
2020                 return false;
2021         }
2022
2023         type = RNA_property_pointer_type(&but->rnapoin, but->rnaprop);
2024         idcode = RNA_type_to_ID_code(type);
2025
2026         return ((but->editstr == NULL) &&
2027                 (idcode == ID_OB || OB_DATA_SUPPORT_ID(idcode)));
2028 }
2029
2030 uiButExtraIconType ui_but_icon_extra_get(uiBut *but)
2031 {
2032         switch (but->type) {
2033                 case UI_BTYPE_TEXT:
2034                         if (ui_but_icon_extra_is_visible_text_clear(but)) {
2035                                 return UI_BUT_ICONEXTRA_CLEAR;
2036                         }
2037                         break;
2038                 case UI_BTYPE_SEARCH_MENU:
2039                         if ((but->flag & UI_BUT_VALUE_CLEAR) == 0) {
2040                                 /* pass */
2041                         }
2042                         else if (ui_but_icon_extra_is_visible_search_unlink(but)) {
2043                                 return UI_BUT_ICONEXTRA_CLEAR;
2044                         }
2045                         else if (ui_but_icon_extra_is_visible_search_eyedropper(but)) {
2046                                 return UI_BUT_ICONEXTRA_EYEDROPPER;
2047                         }
2048                         break;
2049                 default:
2050                         break;
2051         }
2052
2053         return UI_BUT_ICONEXTRA_NONE;
2054 }
2055
2056 /** \} */
2057
2058
2059 static double ui_get_but_scale_unit(uiBut *but, double value)
2060 {
2061         UnitSettings *unit = but->block->unit;
2062         int unit_type = UI_but_unit_type_get(but);
2063
2064         /* Time unit is a bit special, not handled by BKE_scene_unit_scale() for now. */
2065         if (unit_type == PROP_UNIT_TIME) { /* WARNING - using evil_C :| */
2066                 Scene *scene = CTX_data_scene(but->block->evil_C);
2067                 return FRA2TIME(value);
2068         }
2069         else {
2070                 return BKE_scene_unit_scale(unit, RNA_SUBTYPE_UNIT_VALUE(unit_type), value);
2071         }
2072 }
2073
2074 /* str will be overwritten */
2075 void ui_but_convert_to_unit_alt_name(uiBut *but, char *str, size_t maxlen)
2076 {
2077         if (ui_but_is_unit(but)) {
2078                 UnitSettings *unit = but->block->unit;
2079                 int unit_type = UI_but_unit_type_get(but);
2080                 char *orig_str;
2081                 
2082                 orig_str = BLI_strdup(str);
2083                 
2084                 bUnit_ToUnitAltName(str, maxlen, orig_str, unit->system, RNA_SUBTYPE_UNIT_VALUE(unit_type));
2085                 
2086                 MEM_freeN(orig_str);
2087         }
2088 }
2089
2090 /**
2091  * \param float_precision  Override the button precision.
2092  */
2093 static void ui_get_but_string_unit(uiBut *but, char *str, int len_max, double value, bool pad, int float_precision)
2094 {
2095         UnitSettings *unit = but->block->unit;
2096         const bool do_split = (unit->flag & USER_UNIT_OPT_SPLIT) != 0;
2097         int unit_type = UI_but_unit_type_get(but);
2098         int precision;
2099
2100         if (unit->scale_length < 0.0001f) unit->scale_length = 1.0f;  // XXX do_versions
2101
2102         /* Use precision override? */
2103         if (float_precision == -1) {
2104                 /* Sanity checks */
2105                 precision = (int)but->a2;
2106                 if      (precision > UI_PRECISION_FLOAT_MAX) precision = UI_PRECISION_FLOAT_MAX;
2107                 else if (precision == -1)                    precision = 2;
2108         }
2109         else {
2110                 precision = float_precision;
2111         }
2112
2113         bUnit_AsString(str, len_max, ui_get_but_scale_unit(but, value), precision,
2114                        unit->system, RNA_SUBTYPE_UNIT_VALUE(unit_type), do_split, pad);
2115 }
2116
2117 static float ui_get_but_step_unit(uiBut *but, float step_default)
2118 {
2119         int unit_type = RNA_SUBTYPE_UNIT_VALUE(UI_but_unit_type_get(but));
2120         const double step_orig = step_default * UI_PRECISION_FLOAT_SCALE;
2121         /* Scaling up 'step_origg ' here is a bit arbitrary, its just giving better scales from user POV */
2122         const double scale_step = ui_get_but_scale_unit(but, step_orig * 10);
2123         const double step = bUnit_ClosestScalar(scale_step, but->block->unit->system, unit_type);
2124
2125         /* -1 is an error value */
2126         if (step != -1.0) {
2127                 const double scale_unit = ui_get_but_scale_unit(but, 1.0);
2128                 const double step_unit = bUnit_ClosestScalar(scale_unit, but->block->unit->system, unit_type);
2129                 double step_final;
2130
2131                 BLI_assert(step > 0.0);
2132
2133                 step_final = (step / scale_unit) / (double)UI_PRECISION_FLOAT_SCALE;
2134
2135                 if (step == step_unit) {
2136                         /* Logic here is to scale by the original 'step_orig'
2137                          * only when the unit step matches the scaled step.
2138                          *
2139                          * This is needed for units that don't have a wide range of scales (degrees for eg.).
2140                          * Without this we can't select between a single degree, or a 10th of a degree.
2141                          */
2142                         step_final *= step_orig;
2143                 }
2144
2145                 return (float)step_final;
2146         }
2147         else {
2148                 return step_default;
2149         }
2150 }
2151
2152 /**
2153  * \param float_precision  For number buttons the precision to use or -1 to fallback to the button default.
2154  * \param use_exp_float  Use exponent representation of floats when out of reasonable range (outside of 1e3/1e-3).
2155  */
2156 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)
2157 {
2158         if (r_use_exp_float) {
2159                 *r_use_exp_float = false;
2160         }
2161
2162         if (but->rnaprop && ELEM(but->type, UI_BTYPE_TEXT, UI_BTYPE_SEARCH_MENU)) {
2163                 PropertyType type;
2164                 const char *buf = NULL;
2165                 int buf_len;
2166
2167                 type = RNA_property_type(but->rnaprop);
2168
2169                 if (type == PROP_STRING) {
2170                         /* RNA string */
2171                         buf = RNA_property_string_get_alloc(&but->rnapoin, but->rnaprop, str, maxlen, &buf_len);
2172                 }
2173                 else if (type == PROP_ENUM) {
2174                         /* RNA enum */
2175                         int value = RNA_property_enum_get(&but->rnapoin, but->rnaprop);
2176                         if (RNA_property_enum_name(but->block->evil_C, &but->rnapoin, but->rnaprop, value, &buf)) {
2177                                 BLI_strncpy(str, buf, maxlen);
2178                                 buf = str;
2179                         }
2180                 }
2181                 else if (type == PROP_POINTER) {
2182                         /* RNA pointer */
2183                         PointerRNA ptr = RNA_property_pointer_get(&but->rnapoin, but->rnaprop);
2184                         buf = RNA_struct_name_get_alloc(&ptr, str, maxlen, &buf_len);
2185                 }
2186                 else {
2187                         BLI_assert(0);
2188                 }
2189
2190                 if (!buf) {
2191                         str[0] = '\0';
2192                 }
2193                 else if (buf && buf != str) {
2194                         BLI_assert(maxlen <= buf_len + 1);
2195                         /* string was too long, we have to truncate */
2196                         if (ui_but_is_utf8(but)) {
2197                                 BLI_strncpy_utf8(str, buf, maxlen);
2198                         }
2199                         else {
2200                                 BLI_strncpy(str, buf, maxlen);
2201                         }
2202                         MEM_freeN((void *)buf);
2203                 }
2204         }
2205         else if (but->type == UI_BTYPE_TEXT) {
2206                 /* string */
2207                 BLI_strncpy(str, but->poin, maxlen);
2208                 return;
2209         }
2210         else if (but->type == UI_BTYPE_SEARCH_MENU) {
2211                 /* string */
2212                 BLI_strncpy(str, but->poin, maxlen);
2213                 return;
2214         }
2215         else if (ui_but_anim_expression_get(but, str, maxlen)) {
2216                 /* driver expression */
2217         }
2218         else {
2219                 /* number editing */
2220                 double value;
2221
2222                 value = ui_but_value_get(but);
2223
2224                 if (ui_but_is_float(but)) {
2225                         if (ui_but_is_unit(but)) {
2226                                 ui_get_but_string_unit(but, str, maxlen, value, false, float_precision);
2227                         }
2228                         else {
2229                                 int prec = (float_precision == -1) ? ui_but_calc_float_precision(but, value) : float_precision;
2230                                 if (use_exp_float) {
2231                                         const int int_digits_num = integer_digits_f(value);
2232                                         if (int_digits_num < -6 || int_digits_num > 12) {
2233                                                 BLI_snprintf(str, maxlen, "%.*g", prec, value);
2234                                                 if (r_use_exp_float) {
2235                                                         *r_use_exp_float = true;
2236                                                 }
2237                                         }
2238                                         else {
2239                                                 prec -= int_digits_num;
2240                                                 CLAMP(prec, 0, UI_PRECISION_FLOAT_MAX);
2241                                                 BLI_snprintf(str, maxlen, "%.*f", prec, value);
2242                                         }
2243                                 }
2244                                 else {
2245 #if 0                           /* TODO, but will likely break some stuff, so better after 2.79 release. */
2246                                         prec -= int_digits_num;
2247                                         CLAMP(prec, 0, UI_PRECISION_FLOAT_MAX);
2248 #endif
2249                                         BLI_snprintf(str, maxlen, "%.*f", prec, value);
2250                                 }
2251                         }
2252                 }
2253                 else {
2254                         BLI_snprintf(str, maxlen, "%d", (int)value);
2255                 }
2256         }
2257 }
2258 void ui_but_string_get(uiBut *but, char *str, const size_t maxlen)
2259 {
2260         ui_but_string_get_ex(but, str, maxlen, -1, false, NULL);
2261 }
2262
2263 /**
2264  * A version of #ui_but_string_get_ex for dynamic buffer sizes
2265  * (where #ui_but_string_get_max_length returns 0).
2266  *
2267  * \param r_str_size: size of the returned string (including terminator).
2268  */
2269 char *ui_but_string_get_dynamic(uiBut *but, int *r_str_size)
2270 {
2271         char *str = NULL;
2272         *r_str_size = 1;
2273
2274         if (but->rnaprop && ELEM(but->type, UI_BTYPE_TEXT, UI_BTYPE_SEARCH_MENU)) {
2275                 PropertyType type;
2276
2277                 type = RNA_property_type(but->rnaprop);
2278
2279                 if (type == PROP_STRING) {
2280                         /* RNA string */
2281                         str = RNA_property_string_get_alloc(&but->rnapoin, but->rnaprop, NULL, 0, r_str_size);
2282                         (*r_str_size) += 1;
2283                 }
2284                 else if (type == PROP_ENUM) {
2285                         /* RNA enum */
2286                         int value = RNA_property_enum_get(&but->rnapoin, but->rnaprop);
2287                         const char *value_id;
2288                         if (!RNA_property_enum_name(but->block->evil_C, &but->rnapoin, but->rnaprop, value, &value_id)) {
2289                                 value_id = "";
2290                         }
2291
2292                         *r_str_size = strlen(value_id) + 1;
2293                         str = BLI_strdupn(value_id, *r_str_size);
2294                 }
2295                 else if (type == PROP_POINTER) {
2296                         /* RNA pointer */
2297                         PointerRNA ptr = RNA_property_pointer_get(&but->rnapoin, but->rnaprop);
2298                         str = RNA_struct_name_get_alloc(&ptr, NULL, 0, r_str_size);
2299                         (*r_str_size) += 1;
2300                 }
2301                 else {
2302                         BLI_assert(0);
2303                 }
2304         }
2305         else {
2306                 BLI_assert(0);
2307         }
2308
2309         if (UNLIKELY(str == NULL)) {
2310                 /* should never happen, paranoid check */
2311                 *r_str_size = 1;
2312                 str = BLI_strdup("");
2313                 BLI_assert(0);
2314
2315         }
2316
2317         return str;
2318 }
2319
2320 #ifdef WITH_PYTHON
2321
2322 static bool ui_set_but_string_eval_num_unit(bContext *C, uiBut *but, const char *str, double *r_value)
2323 {
2324         char str_unit_convert[256];
2325         const int unit_type = UI_but_unit_type_get(but);
2326
2327         BLI_strncpy(str_unit_convert, str, sizeof(str_unit_convert));
2328
2329         /* ugly, use the draw string to get the value,
2330          * this could cause problems if it includes some text which resolves to a unit */
2331         bUnit_ReplaceString(str_unit_convert, sizeof(str_unit_convert), but->drawstr,
2332                             ui_get_but_scale_unit(but, 1.0), but->block->unit->system, RNA_SUBTYPE_UNIT_VALUE(unit_type));
2333
2334         return BPY_execute_string_as_number(C, str_unit_convert, true, r_value);
2335 }
2336
2337 #endif /* WITH_PYTHON */
2338
2339
2340 bool ui_but_string_set_eval_num(bContext *C, uiBut *but, const char *str, double *r_value)
2341 {
2342         bool ok = false;
2343
2344 #ifdef WITH_PYTHON
2345
2346         if (str[0] != '\0') {
2347                 bool is_unit_but = (ui_but_is_float(but) && ui_but_is_unit(but));
2348                 /* only enable verbose if we won't run again with units */
2349                 if (BPY_execute_string_as_number(C, str, is_unit_but == false, r_value)) {
2350                         /* if the value parsed ok without unit conversion this button may still need a unit multiplier */
2351                         if (is_unit_but) {
2352                                 char str_new[128];
2353
2354                                 BLI_snprintf(str_new, sizeof(str_new), "%f", *r_value);
2355                                 ok = ui_set_but_string_eval_num_unit(C, but, str_new, r_value);
2356                         }
2357                         else {
2358                                 ok = true; /* parse normal string via py (no unit conversion needed) */
2359                         }
2360                 }
2361                 else if (is_unit_but) {
2362                         /* parse failed, this is a unit but so run replacements and parse again */
2363                         ok = ui_set_but_string_eval_num_unit(C, but, str, r_value);
2364                 }
2365         }
2366
2367 #else /* WITH_PYTHON */
2368
2369         *r_value = atof(str);
2370         ok = true;
2371
2372         UNUSED_VARS(C, but);
2373
2374 #endif /* WITH_PYTHON */
2375
2376         return ok;
2377 }
2378
2379 /* just the assignment/free part */
2380 static void ui_but_string_set_internal(uiBut *but, const char *str, size_t str_len)
2381 {
2382         BLI_assert(str_len == strlen(str));
2383         BLI_assert(but->str == NULL);
2384         str_len += 1;
2385
2386         if (str_len > UI_MAX_NAME_STR) {
2387                 but->str = MEM_mallocN(str_len, "ui_def_but str");
2388         }
2389         else {
2390                 but->str = but->strdata;
2391         }
2392         memcpy(but->str, str, str_len);
2393 }
2394
2395 static void ui_but_string_free_internal(uiBut *but)
2396 {
2397         if (but->str) {
2398                 if (but->str != but->strdata) {
2399                         MEM_freeN(but->str);
2400                 }
2401                 /* must call 'ui_but_string_set_internal' after */
2402                 but->str = NULL;
2403         }
2404 }
2405
2406 bool ui_but_string_set(bContext *C, uiBut *but, const char *str)
2407 {
2408         if (but->rnaprop && but->rnapoin.data && ELEM(but->type, UI_BTYPE_TEXT, UI_BTYPE_SEARCH_MENU)) {
2409                 if (RNA_property_editable(&but->rnapoin, but->rnaprop)) {
2410                         PropertyType type;
2411
2412                         type = RNA_property_type(but->rnaprop);
2413
2414                         if (type == PROP_STRING) {
2415                                 /* RNA string */
2416                                 RNA_property_string_set(&but->rnapoin, but->rnaprop, str);
2417                                 return true;
2418                         }
2419                         else if (type == PROP_POINTER) {
2420                                 /* RNA pointer */
2421                                 PointerRNA ptr, rptr;
2422                                 PropertyRNA *prop;
2423
2424                                 if (str[0] == '\0') {
2425                                         RNA_property_pointer_set(&but->rnapoin, but->rnaprop, PointerRNA_NULL);
2426                                         return true;
2427                                 }
2428                                 else {
2429                                         ptr = but->rnasearchpoin;
2430                                         prop = but->rnasearchprop;
2431                                         
2432                                         if (prop && RNA_property_collection_lookup_string(&ptr, prop, str, &rptr))
2433                                                 RNA_property_pointer_set(&but->rnapoin, but->rnaprop, rptr);
2434
2435                                         return true;
2436                                 }
2437
2438                                 return false;
2439                         }
2440                         else if (type == PROP_ENUM) {
2441                                 int value;
2442                                 if (RNA_property_enum_value(but->block->evil_C, &but->rnapoin, but->rnaprop, str, &value)) {
2443                                         RNA_property_enum_set(&but->rnapoin, but->rnaprop, value);
2444                                         return true;
2445                                 }
2446                                 return false;
2447                         }
2448                         else {
2449                                 BLI_assert(0);
2450                         }
2451                 }
2452         }
2453         else if (but->type == UI_BTYPE_TEXT) {
2454                 /* string */
2455                 if (!but->poin || (str[0] == '\0')) {
2456                         str = "";
2457                 }
2458                 else if (ui_but_is_utf8(but)) {
2459                         BLI_strncpy_utf8(but->poin, str, but->hardmax);
2460                 }
2461                 else {
2462                         BLI_strncpy(but->poin, str, but->hardmax);
2463                 }
2464
2465                 return true;
2466         }
2467         else if (but->type == UI_BTYPE_SEARCH_MENU) {
2468                 /* string */
2469                 BLI_strncpy(but->poin, str, but->hardmax);
2470                 return true;
2471         }
2472         else if (ui_but_anim_expression_set(but, str)) {
2473                 /* driver expression */
2474                 return true;
2475         }
2476         else if (str[0] == '#') {
2477                 /* shortcut to create new driver expression (versus immediate Py-execution) */
2478                 return ui_but_anim_expression_create(but, str + 1);
2479         }
2480         else {
2481                 /* number editing */
2482                 double value;
2483
2484                 if (ui_but_string_set_eval_num(C, but, str, &value) == false) {
2485                         WM_report_banner_show();
2486                         return false;
2487                 }
2488
2489                 if (!ui_but_is_float(but)) {
2490                         value = floor(value + 0.5);
2491                 }
2492
2493                 /* not that we use hard limits here */
2494                 if (value < (double)but->hardmin) value = but->hardmin;
2495                 if (value > (double)but->hardmax) value = but->hardmax;
2496
2497                 ui_but_value_set(but, value);
2498                 return true;
2499         }
2500
2501         return false;
2502 }
2503
2504 void ui_but_default_set(bContext *C, const bool all, const bool use_afterfunc)
2505 {
2506         wmOperatorType *ot = WM_operatortype_find("UI_OT_reset_default_button", true);
2507
2508         if (use_afterfunc) {
2509                 PointerRNA *ptr;
2510                 ptr = ui_handle_afterfunc_add_operator(ot, WM_OP_EXEC_DEFAULT, true);
2511                 RNA_boolean_set(ptr, "all", all);
2512         }
2513         else {
2514                 PointerRNA ptr;
2515                 WM_operator_properties_create_ptr(&ptr, ot);
2516                 RNA_boolean_set(&ptr, "all", all);
2517                 WM_operator_name_call_ptr(C, ot, WM_OP_EXEC_DEFAULT, &ptr);
2518                 WM_operator_properties_free(&ptr);
2519         }
2520 }
2521
2522 static double soft_range_round_up(double value, double max)
2523 {
2524         /* round up to .., 0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50, ..
2525          * checking for 0.0 prevents floating point exceptions */
2526         double newmax = (value != 0.0) ? pow(10.0, ceil(log(value) / M_LN10)) : 0.0;
2527
2528         if (newmax * 0.2 >= max && newmax * 0.2 >= value)
2529                 return newmax * 0.2;
2530         else if (newmax * 0.5 >= max && newmax * 0.5 >= value)
2531                 return newmax * 0.5;
2532         else
2533                 return newmax;
2534 }
2535
2536 static double soft_range_round_down(double value, double max)
2537 {
2538         /* round down to .., 0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50, ..
2539          * checking for 0.0 prevents floating point exceptions */
2540         double newmax = (value != 0.0) ? pow(10.0, floor(log(value) / M_LN10)) : 0.0;
2541
2542         if (newmax * 5.0 <= max && newmax * 5.0 <= value)
2543                 return newmax * 5.0;
2544         else if (newmax * 2.0 <= max && newmax * 2.0 <= value)
2545                 return newmax * 2.0;
2546         else
2547                 return newmax;
2548 }
2549
2550 /* note: this could be split up into functions which handle arrays and not */
2551 static void ui_set_but_soft_range(uiBut *but)
2552 {
2553         /* ideally we would not limit this but practically, its more than
2554          * enough worst case is very long vectors wont use a smart soft-range
2555          * which isn't so bad. */
2556
2557         if (but->rnaprop) {
2558                 const PropertyType type = RNA_property_type(but->rnaprop);
2559                 double softmin, softmax /*, step, precision*/;
2560                 double value_min;
2561                 double value_max;
2562
2563                 /* clamp button range to something reasonable in case
2564                  * we get -inf/inf from RNA properties */
2565                 if (type == PROP_INT) {
2566                         const bool is_array = RNA_property_array_check(but->rnaprop);
2567                         int imin, imax, istep;
2568
2569                         RNA_property_int_ui_range(&but->rnapoin, but->rnaprop, &imin, &imax, &istep);
2570                         softmin = (imin == INT_MIN) ? -1e4 : imin;
2571                         softmax = (imin == INT_MAX) ? 1e4 : imax;
2572                         /*step = istep;*/ /*UNUSED*/
2573                         /*precision = 1;*/ /*UNUSED*/
2574
2575                         if (is_array) {
2576                                 int value_range[2];
2577                                 RNA_property_int_get_array_range(&but->rnapoin, but->rnaprop, value_range);
2578                                 value_min = (double)value_range[0];
2579                                 value_max = (double)value_range[1];
2580                         }
2581                         else {
2582                                 value_min = value_max = (double)RNA_property_int_get(&but->rnapoin, but->rnaprop);
2583                         }
2584                 }
2585                 else if (type == PROP_FLOAT) {
2586                         const bool is_array = RNA_property_array_check(but->rnaprop);
2587                         float fmin, fmax, fstep, fprecision;
2588
2589                         RNA_property_float_ui_range(&but->rnapoin, but->rnaprop, &fmin, &fmax, &fstep, &fprecision);
2590                         softmin = (fmin == -FLT_MAX) ? (float)-1e4 : fmin;
2591                         softmax = (fmax == FLT_MAX) ? (float)1e4 : fmax;
2592                         /*step = fstep;*/ /*UNUSED*/
2593                         /*precision = fprecision;*/ /*UNUSED*/
2594
2595                         if (is_array) {
2596                                 float value_range[2];
2597                                 RNA_property_float_get_array_range(&but->rnapoin, but->rnaprop, value_range);
2598                                 value_min = (double)value_range[0];
2599                                 value_max = (double)value_range[1];
2600                         }
2601                         else {
2602                                 value_min = value_max = (double)RNA_property_float_get(&but->rnapoin, but->rnaprop);
2603                         }
2604                 }
2605                 else {
2606                         return;
2607                 }
2608
2609                 /* if the value goes out of the soft/max range, adapt the range */
2610                 if (value_min + 1e-10 < softmin) {
2611                         if (value_min < 0.0)
2612                                 softmin = -soft_range_round_up(-value_min, -softmin);
2613                         else
2614                                 softmin = soft_range_round_down(value_min, softmin);
2615
2616                         if (softmin < (double)but->hardmin)
2617                                 softmin = (double)but->hardmin;
2618                 }
2619                 if (value_max - 1e-10 > softmax) {
2620                         if (value_max < 0.0)
2621                                 softmax = -soft_range_round_down(-value_max, -softmax);
2622                         else
2623                                 softmax = soft_range_round_up(value_max, softmax);
2624
2625                         if (softmax > (double)but->hardmax)
2626                                 softmax = but->hardmax;
2627                 }
2628
2629                 but->softmin = softmin;
2630                 but->softmax = softmax;
2631         }
2632         else if (but->poin && (but->pointype & UI_BUT_POIN_TYPES)) {
2633                 float value = ui_but_value_get(but);
2634                 if (isfinite(value)) {
2635                         CLAMP(value, but->hardmin, but->hardmax);
2636                         but->softmin = min_ff(but->softmin, value);
2637                         but->softmax = max_ff(but->softmax, value);
2638                 }
2639         }
2640         else {
2641                 BLI_assert(0);
2642         }
2643 }
2644
2645 /* ******************* Free ********************/
2646
2647 static void ui_free_link(uiLink *link)
2648 {
2649         if (link) {
2650                 BLI_freelistN(&link->lines);
2651                 MEM_freeN(link);
2652         }
2653 }
2654
2655 /* can be called with C==NULL */
2656 static void ui_but_free(const bContext *C, uiBut *but)
2657 {
2658         if (but->opptr) {
2659                 WM_operator_properties_free(but->opptr);
2660                 MEM_freeN(but->opptr);
2661         }
2662
2663         if (but->func_argN) {
2664                 MEM_freeN(but->func_argN);
2665         }
2666
2667         if (but->tip_argN) {
2668                 MEM_freeN(but->tip_argN);
2669         }
2670
2671         if (!but->editstr && but->free_search_arg) {
2672                 MEM_SAFE_FREE(but->search_arg);
2673         }
2674
2675         if (but->active) {
2676                 /* XXX solve later, buttons should be free-able without context ideally,
2677                  * however they may have open tooltips or popup windows, which need to
2678                  * be closed using a context pointer */
2679                 if (C) {
2680                         ui_but_active_free(C, but);
2681                 }
2682                 else {
2683                         if (but->active) {
2684                                 MEM_freeN(but->active);
2685                         }
2686                 }
2687         }
2688         if (but->str && but->str != but->strdata) {
2689                 MEM_freeN(but->str);
2690         }
2691         ui_free_link(but->link);
2692
2693         if ((but->type == UI_BTYPE_IMAGE) && but->poin) {
2694                 IMB_freeImBuf((struct ImBuf *)but->poin);
2695         }
2696
2697         if (but->dragpoin && (but->dragflag & UI_BUT_DRAGPOIN_FREE)) {
2698                 MEM_freeN(but->dragpoin);
2699         }
2700
2701         BLI_assert(UI_butstore_is_registered(but->block, but) == false);
2702
2703         MEM_freeN(but);
2704 }
2705
2706 /* can be called with C==NULL */
2707 void UI_block_free(const bContext *C, uiBlock *block)
2708 {
2709         uiBut *but;
2710
2711         UI_butstore_clear(block);
2712
2713         while ((but = BLI_pophead(&block->buttons))) {
2714                 ui_but_free(C, but);
2715         }
2716
2717         if (block->unit) {
2718                 MEM_freeN(block->unit);
2719         }
2720
2721         if (block->func_argN) {
2722                 MEM_freeN(block->func_argN);
2723         }
2724
2725         CTX_store_free_list(&block->contexts);
2726
2727         BLI_freelistN(&block->saferct);
2728         BLI_freelistN(&block->color_pickers.list);
2729         
2730         MEM_freeN(block);
2731 }
2732
2733 /* can be called with C==NULL */
2734 void UI_blocklist_free(const bContext *C, ListBase *lb)
2735 {
2736         uiBlock *block;
2737         
2738         while ((block = BLI_pophead(lb))) {
2739                 UI_block_free(C, block);
2740         }
2741 }
2742
2743 void UI_blocklist_free_inactive(const bContext *C, ListBase *lb)
2744 {
2745         uiBlock *block, *nextblock;
2746
2747         for (block = lb->first; block; block = nextblock) {
2748                 nextblock = block->next;
2749         
2750                 if (!block->handle) {
2751                         if (!block->active) {
2752                                 BLI_remlink(lb, block);
2753                                 UI_block_free(C, block);
2754                         }
2755                         else
2756                                 block->active = 0;
2757                 }
2758         }
2759 }
2760
2761 void UI_block_region_set(uiBlock *block, ARegion *region)
2762 {
2763         ListBase *lb = &region->uiblocks;
2764         uiBlock *oldblock = NULL;
2765
2766         /* each listbase only has one block with this name, free block
2767          * if is already there so it can be rebuilt from scratch */
2768         if (lb) {
2769                 oldblock = BLI_findstring(lb, block->name, offsetof(uiBlock, name));
2770
2771                 if (oldblock) {
2772                         oldblock->active = 0;
2773                         oldblock->panel = NULL;
2774                         oldblock->handle = NULL;
2775                 }
2776
2777                 /* at the beginning of the list! for dynamical menus/blocks */
2778                 BLI_addhead(lb, block);
2779         }
2780
2781         block->oldblock = oldblock;
2782 }
2783
2784 uiBlock *UI_block_begin(const bContext *C, ARegion *region, const char *name, short dt)
2785 {
2786         uiBlock *block;
2787         wmWindow *window;
2788         Scene *scn;
2789         int getsizex, getsizey;
2790
2791         window = CTX_wm_window(C);
2792         scn = CTX_data_scene(C);
2793
2794         block = MEM_callocN(sizeof(uiBlock), "uiBlock");
2795         block->active = 1;
2796         block->dt = dt;
2797         block->evil_C = (void *)C;  /* XXX */
2798
2799         if (scn) {
2800                 block->color_profile = true;
2801
2802                 /* store display device name, don't lookup for transformations yet
2803                  * block could be used for non-color displays where looking up for transformation
2804                  * would slow down redraw, so only lookup for actual transform when it's indeed
2805                  * needed
2806                  */
2807                 BLI_strncpy(block->display_device, scn->display_settings.display_device, sizeof(block->display_device));
2808
2809                 /* copy to avoid crash when scene gets deleted with ui still open */
2810                 block->unit = MEM_mallocN(sizeof(scn->unit), "UI UnitSettings");
2811                 memcpy(block->unit, &scn->unit, sizeof(scn->unit));
2812         }
2813
2814         BLI_strncpy(block->name, name, sizeof(block->name));
2815
2816         if (region)
2817                 UI_block_region_set(block, region);
2818
2819         /* window matrix and aspect */
2820         if (region && region->swinid) {
2821                 wm_subwindow_matrix_get(window, region->swinid, block->winmat);
2822                 wm_subwindow_size_get(window, region->swinid, &getsizex, &getsizey);
2823
2824                 block->aspect = 2.0f / fabsf(getsizex * block->winmat[0][0]);
2825         }
2826         else {
2827                 const bScreen *screen = WM_window_get_active_screen(window);
2828
2829                 /* no subwindow created yet, for menus for example, so we
2830                  * use the main window instead, since buttons are created
2831                  * there anyway */
2832                 wm_subwindow_matrix_get(window, screen->mainwin, block->winmat);
2833                 wm_subwindow_size_get(window, screen->mainwin, &getsizex, &getsizey);
2834
2835                 block->aspect = 2.0f / fabsf(getsizex * block->winmat[0][0]);
2836                 block->auto_open = true;
2837                 block->flag |= UI_BLOCK_LOOP; /* tag as menu */
2838         }
2839
2840         return block;
2841 }
2842
2843 uiBlock *UI_block_find_in_region(const char *name, ARegion *ar)
2844 {
2845         return BLI_findstring(&ar->uiblocks, name, offsetof(uiBlock, name));
2846 }
2847
2848 void UI_block_emboss_set(uiBlock *block, char dt)
2849 {
2850         block->dt = dt;
2851 }
2852
2853 /**
2854  * \param but: Button to update.
2855  * \param validate: When set, this function may change the button value.
2856  * Otherwise treat the button value as read-only.
2857  */
2858 void ui_but_update_ex(uiBut *but, const bool validate)
2859 {
2860         /* if something changed in the button */
2861         double value = UI_BUT_VALUE_UNSET;
2862 //      float okwidth; // UNUSED
2863         
2864         ui_but_update_select_flag(but, &value);
2865         
2866         /* only update soft range while not editing */
2867         if (!(but->editval || but->editstr || but->editvec)) {
2868                 if ((but->rnaprop != NULL) ||
2869                     (but->poin && (but->pointype & UI_BUT_POIN_TYPES)))
2870                 {
2871                         ui_set_but_soft_range(but);
2872                 }
2873         }
2874
2875         /* test for min and max, icon sliders, etc */
2876         switch (but->type) {
2877                 case UI_BTYPE_NUM:
2878                 case UI_BTYPE_SCROLL:
2879                 case UI_BTYPE_NUM_SLIDER:
2880                         if (validate) {
2881                                 UI_GET_BUT_VALUE_INIT(but, value);
2882                                 if      (value < (double)but->hardmin) {
2883                                         ui_but_value_set(but, but->hardmin);
2884                                 }
2885                                 else if (value > (double)but->hardmax) {
2886                                         ui_but_value_set(but, but->hardmax);
2887                                 }
2888
2889                                 /* max must never be smaller than min! Both being equal is allowed though */
2890                                 BLI_assert(but->softmin <= but->softmax &&
2891                                            but->hardmin <= but->hardmax);
2892                         }
2893                         break;
2894                         
2895                 case UI_BTYPE_ICON_TOGGLE:
2896                 case UI_BTYPE_ICON_TOGGLE_N:
2897                         if (!but->rnaprop || (RNA_property_flag(but->rnaprop) & PROP_ICONS_CONSECUTIVE)) {
2898                                 if (but->flag & UI_SELECT) but->iconadd = 1;
2899                                 else but->iconadd = 0;
2900                         }
2901                         break;
2902                         
2903                         /* quiet warnings for unhandled types */
2904                 default:
2905                         break;
2906         }
2907         
2908         
2909         /* safety is 4 to enable small number buttons (like 'users') */
2910         // okwidth = -4 + (BLI_rcti_size_x(&but->rect)); // UNUSED
2911         
2912         /* name: */
2913         switch (but->type) {
2914
2915                 case UI_BTYPE_MENU:
2916                         if (BLI_rctf_size_x(&but->rect) > 24.0f) {
2917                                 /* only needed for menus in popup blocks that don't recreate buttons on redraw */
2918                                 if (but->block->flag & UI_BLOCK_LOOP) {
2919                                         if (but->rnaprop && (RNA_property_type(but->rnaprop) == PROP_ENUM)) {
2920                                                 int value_enum = RNA_property_enum_get(&but->rnapoin, but->rnaprop);
2921
2922                                                 EnumPropertyItem item;
2923                                                 if (RNA_property_enum_item_from_value_gettexted(
2924                                                         but->block->evil_C,
2925                                                         &but->rnapoin, but->rnaprop, value_enum, &item))
2926                                                 {
2927                                                         size_t slen = strlen(item.name);
2928                                                         ui_but_string_free_internal(but);
2929                                                         ui_but_string_set_internal(but, item.name, slen);
2930                                                         but->icon = item.icon;
2931                                                 }
2932                                         }
2933                                 }
2934                                 BLI_strncpy(but->drawstr, but->str, sizeof(but->drawstr));
2935                         }
2936                         break;
2937
2938                 case UI_BTYPE_NUM:
2939                 case UI_BTYPE_NUM_SLIDER:
2940
2941                         if (!but->editstr) {
2942                                 const char *drawstr_suffix = NULL;
2943                                 size_t slen;
2944
2945                                 UI_GET_BUT_VALUE_INIT(but, value);
2946
2947                                 slen = BLI_strncpy_rlen(but->drawstr, but->str, sizeof(but->drawstr));
2948
2949                                 if (ui_but_is_float(but)) {
2950                                         if (value == (double) FLT_MAX) {
2951                                                 slen += BLI_strncpy_rlen(but->drawstr + slen, "inf", sizeof(but->drawstr) - slen);
2952                                         }
2953                                         else if (value == (double) -FLT_MAX) {
2954                                                 slen += BLI_strncpy_rlen(but->drawstr + slen, "-inf", sizeof(but->drawstr) - slen);
2955                                         }
2956                                         /* support length type buttons */
2957                                         else if (ui_but_is_unit(but)) {
2958                                                 char new_str[sizeof(but->drawstr)];
2959                                                 ui_get_but_string_unit(but, new_str, sizeof(new_str), value, true, -1);
2960                                                 slen += BLI_strncpy_rlen(but->drawstr + slen, new_str, sizeof(but->drawstr) - slen);
2961                                         }
2962                                         else {
2963                                                 const int prec = ui_but_calc_float_precision(but, value);
2964                                                 slen += BLI_snprintf_rlen(but->drawstr + slen, sizeof(but->drawstr) - slen, "%.*f", prec, value);
2965                                         }
2966                                 }
2967                                 else {
2968                                         slen += BLI_snprintf_rlen(but->drawstr + slen, sizeof(but->drawstr) - slen, "%d", (int)value);
2969                                 }
2970
2971                                 if (but->rnaprop) {
2972                                         PropertySubType pstype = RNA_property_subtype(but->rnaprop);
2973
2974                                         if (pstype == PROP_PERCENTAGE) {
2975                                                 drawstr_suffix = "%";
2976                                         }
2977                                         else if (pstype == PROP_PIXEL) {
2978                                                 drawstr_suffix = " px";
2979                                         }
2980                                 }
2981
2982                                 if (drawstr_suffix) {
2983                                         BLI_strncpy(but->drawstr + slen, drawstr_suffix, sizeof(but->drawstr) - slen);
2984                                 }
2985
2986                         }
2987                         break;
2988
2989                 case UI_BTYPE_LABEL:
2990                         if (ui_but_is_float(but)) {
2991                                 int prec;
2992                                 UI_GET_BUT_VALUE_INIT(but, value);
2993                                 prec = ui_but_calc_float_precision(but, value);
2994                                 BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s%.*f", but->str, prec, value);
2995                         }
2996                         else {
2997                                 BLI_strncpy(but->drawstr, but->str, UI_MAX_DRAW_STR);
2998                         }
2999                 
3000                         break;
3001
3002                 case UI_BTYPE_TEXT:
3003                 case UI_BTYPE_SEARCH_MENU:
3004                         if (!but->editstr) {
3005                                 char str[UI_MAX_DRAW_STR];
3006
3007                                 ui_but_string_get(but, str, UI_MAX_DRAW_STR);
3008                                 BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s%s", but->str, str);
3009                         }
3010                         break;
3011         
3012                 case UI_BTYPE_KEY_EVENT:
3013                 {
3014                         const char *str;
3015                         if (but->flag & UI_SELECT) {
3016                                 str = "Press a key";
3017                         }
3018                         else {
3019                                 UI_GET_BUT_VALUE_INIT(but, value);
3020                                 str = WM_key_event_string((short)value, false);
3021                         }
3022                         BLI_snprintf(but->drawstr, UI_MAX_DRAW_STR, "%s%s", but->str, str);
3023                         break;
3024                 }
3025                 case UI_BTYPE_HOTKEY_EVENT:
3026                         if (but->flag & UI_SELECT) {
3027
3028                                 if (but->modifier_key) {
3029                                         char *str = but->drawstr;
3030                                         but->drawstr[0] = '\0';
3031
3032                                         if (but->modifier_key & KM_SHIFT)
3033                                                 str += BLI_strcpy_rlen(str, "Shift ");
3034                                         if (but->modifier_key & KM_CTRL)
3035                                                 str += BLI_strcpy_rlen(str, "Ctrl ");
3036                                         if (but->modifier_key & KM_ALT)
3037                                                 str += BLI_strcpy_rlen(str, "Alt ");
3038                                         if (but->modifier_key & KM_OSKEY)
3039                                                 str += BLI_strcpy_rlen(str, "Cmd ");
3040
3041                                         (void)str; /* UNUSED */
3042                                 }
3043                                 else {
3044                                         BLI_strncpy(but->drawstr, "Press a key", UI_MAX_DRAW_STR);
3045                                 }
3046                         }
3047                         else
3048                                 BLI_strncpy(but->drawstr, but->str, UI_MAX_DRAW_STR);
3049
3050                         break;
3051
3052                 case UI_BTYPE_HSVCUBE:
3053                 case UI_BTYPE_HSVCIRCLE:
3054                         break;
3055                 default:
3056                         BLI_strncpy(but->drawstr, but->str, UI_MAX_DRAW_STR);
3057                         break;
3058                 
3059         }
3060
3061         /* if we are doing text editing, this will override the drawstr */
3062         if (but->editstr)
3063                 but->drawstr[0] = '\0';
3064         
3065         /* text clipping moved to widget drawing code itself */
3066 }
3067
3068 void ui_but_update(uiBut *but)
3069 {
3070         ui_but_update_ex(but, false);
3071 }
3072
3073 void ui_but_update_edited(uiBut *but)
3074 {
3075         ui_but_update_ex(but, true);
3076 }
3077
3078 void UI_block_align_begin(uiBlock *block)
3079 {
3080         /* if other align was active, end it */
3081         if (block->flag & UI_BUT_ALIGN) UI_block_align_end(block);
3082
3083         block->flag |= UI_BUT_ALIGN_DOWN;
3084         block->alignnr++;
3085
3086         /* buttons declared after this call will get this align nr */ // XXX flag?
3087 }
3088
3089 void UI_block_align_end(uiBlock *block)
3090 {
3091         block->flag &= ~UI_BUT_ALIGN;  /* all 4 flags */
3092 }
3093
3094 struct ColorManagedDisplay *ui_block_cm_display_get(uiBlock *block)
3095 {
3096         return IMB_colormanagement_display_get_named(block->display_device);
3097 }
3098
3099 void ui_block_cm_to_display_space_v3(uiBlock *block, float pixel[3])
3100 {
3101         struct ColorManagedDisplay *display = ui_block_cm_display_get(block);
3102
3103         IMB_colormanagement_scene_linear_to_display_v3(pixel, display);
3104 }
3105
3106 void ui_block_cm_to_scene_linear_v3(uiBlock *block, float pixel[3])
3107 {
3108     &nbs