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