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