eb12f19cf1d14808e79f65ffa98974fb306ccfe8
[blender-staging.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         BLI_movelisttolist(&block->color_pickers.list, &block->oldblock->color_pickers.list);
1174
1175         block->oldblock = NULL;
1176 }
1177
1178 void uiEndBlock_ex(const bContext *C, uiBlock *block, const int xy[2])
1179 {
1180         wmWindow *window = CTX_wm_window(C);
1181         Scene *scene = CTX_data_scene(C);
1182         uiBut *but;
1183
1184         BLI_assert(block->active);
1185
1186         uiBlockUpdateFromOld(C, block);
1187
1188         /* inherit flags from 'old' buttons that was drawn here previous, based
1189          * on matching buttons, we need this to make button event handling non
1190          * blocking, while still allowing buttons to be remade each redraw as it
1191          * is expected by blender code */
1192         for (but = block->buttons.first; but; but = but->next) {
1193                 /* temp? Proper check for graying out */
1194                 if (but->optype) {
1195                         wmOperatorType *ot = but->optype;
1196
1197                         if (but->context)
1198                                 CTX_store_set((bContext *)C, but->context);
1199
1200                         if (ot == NULL || WM_operator_poll_context((bContext *)C, ot, but->opcontext) == 0) {
1201                                 but->flag |= UI_BUT_DISABLED;
1202                                 but->lock = true;
1203                         }
1204
1205                         if (but->context)
1206                                 CTX_store_set((bContext *)C, NULL);
1207                 }
1208
1209                 ui_but_anim_flag(but, (scene) ? scene->r.cfra : 0.0f);
1210         }
1211
1212
1213
1214         /* handle pending stuff */
1215         if (block->layouts.first) {
1216                 uiBlockLayoutResolve(block, NULL, NULL);
1217         }
1218         ui_block_do_align(block);
1219         if ((block->flag & UI_BLOCK_LOOP) && (block->flag & UI_BLOCK_NUMSELECT)) {
1220                 ui_menu_block_set_keyaccels(block); /* could use a different flag to check */
1221         }
1222
1223         if (block->flag & UI_BLOCK_LOOP) {
1224                 ui_menu_block_set_keymaps(C, block);
1225         }
1226         
1227         /* after keymaps! */
1228         switch (block->bounds_type) {
1229                 case UI_BLOCK_BOUNDS_NONE:
1230                         break;
1231                 case UI_BLOCK_BOUNDS:
1232                         ui_bounds_block(block);
1233                         break;
1234                 case UI_BLOCK_BOUNDS_TEXT:
1235                         ui_text_bounds_block(block, 0.0f);
1236                         break;
1237                 case UI_BLOCK_BOUNDS_POPUP_CENTER:
1238                         ui_centered_bounds_block(window, block);
1239                         break;
1240                 case UI_BLOCK_BOUNDS_PIE_CENTER:
1241                         ui_centered_pie_bounds_block(block);
1242                         break;
1243
1244                         /* fallback */
1245                 case UI_BLOCK_BOUNDS_POPUP_MOUSE:
1246                 case UI_BLOCK_BOUNDS_POPUP_MENU:
1247                         ui_popup_bounds_block(window, block, block->bounds_type, xy);
1248                         break;
1249         }
1250
1251         if (block->rect.xmin == 0.0f && block->rect.xmax == 0.0f) {
1252                 uiBoundsBlock(block, 0);
1253         }
1254         if (block->flag & UI_BUT_ALIGN) {
1255                 uiBlockEndAlign(block);
1256         }
1257
1258         block->endblock = 1;
1259 }
1260
1261 void uiEndBlock(const bContext *C, uiBlock *block)
1262 {
1263         wmWindow *window = CTX_wm_window(C);
1264
1265         uiEndBlock_ex(C, block, &window->eventstate->x);
1266 }
1267
1268 /* ************** BLOCK DRAWING FUNCTION ************* */
1269
1270 void ui_fontscale(short *points, float aspect)
1271 {
1272         if (aspect < 0.9f || aspect > 1.1f) {
1273                 float pointsf = *points;
1274                 
1275                 /* for some reason scaling fonts goes too fast compared to widget size */
1276                 /* XXX not true anymore? (ton) */
1277                 //aspect = sqrt(aspect);
1278                 pointsf /= aspect;
1279                 
1280                 if (aspect > 1.0f)
1281                         *points = ceilf(pointsf);
1282                 else
1283                         *points = floorf(pointsf);
1284         }
1285 }
1286
1287 /* project button or block (but==NULL) to pixels in regionspace */
1288 static void ui_but_to_pixelrect(rcti *rect, const ARegion *ar, uiBlock *block, uiBut *but)
1289 {
1290         rctf rectf;
1291
1292         ui_block_to_window_rctf(ar, block, &rectf, (but) ? &but->rect : &block->rect);
1293
1294         rectf.xmin -= ar->winrct.xmin;
1295         rectf.ymin -= ar->winrct.ymin;
1296         rectf.xmax -= ar->winrct.xmin;
1297         rectf.ymax -= ar->winrct.ymin;
1298
1299         rect->xmin = floorf(rectf.xmin);
1300         rect->ymin = floorf(rectf.ymin);
1301         rect->xmax = floorf(rectf.xmax);
1302         rect->ymax = floorf(rectf.ymax);
1303 }
1304
1305 /* uses local copy of style, to scale things down, and allow widgets to change stuff */
1306 void uiDrawBlock(const bContext *C, uiBlock *block)
1307 {
1308         uiStyle style = *UI_GetStyleDraw();  /* XXX pass on as arg */
1309         ARegion *ar;
1310         uiBut *but;
1311         rcti rect;
1312         int multisample_enabled;
1313         
1314         /* get menu region or area region */
1315         ar = CTX_wm_menu(C);
1316         if (!ar)
1317                 ar = CTX_wm_region(C);
1318
1319         if (!block->endblock)
1320                 uiEndBlock(C, block);
1321
1322         /* disable AA, makes widgets too blurry */
1323         multisample_enabled = glIsEnabled(GL_MULTISAMPLE_ARB);
1324         if (multisample_enabled)
1325                 glDisable(GL_MULTISAMPLE_ARB);
1326
1327         /* we set this only once */
1328         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1329         
1330         /* scale fonts */
1331         ui_fontscale(&style.paneltitle.points, block->aspect);
1332         ui_fontscale(&style.grouplabel.points, block->aspect);
1333         ui_fontscale(&style.widgetlabel.points, block->aspect);
1334         ui_fontscale(&style.widget.points, block->aspect);
1335         
1336         /* scale block min/max to rect */
1337         ui_but_to_pixelrect(&rect, ar, block, NULL);
1338         
1339         /* pixel space for AA widgets */
1340         glMatrixMode(GL_PROJECTION);
1341         glPushMatrix();
1342         glMatrixMode(GL_MODELVIEW);
1343         glPushMatrix();
1344         glLoadIdentity();
1345
1346         wmOrtho2_region_ui(ar);
1347         
1348         /* back */
1349         if (block->flag & UI_BLOCK_RADIAL)
1350                 ui_draw_pie_center(block);
1351         else if (block->flag & UI_BLOCK_LOOP)
1352                 ui_draw_menu_back(&style, block, &rect);
1353         else if (block->panel)
1354                 ui_draw_aligned_panel(&style, block, &rect, UI_panel_category_is_visible(ar));
1355
1356         /* widgets */
1357         for (but = block->buttons.first; but; but = but->next) {
1358                 if (!(but->flag & (UI_HIDDEN | UI_SCROLLED))) {
1359                         ui_but_to_pixelrect(&rect, ar, block, but);
1360                 
1361                         /* XXX: figure out why invalid coordinates happen when closing render window */
1362                         /* and material preview is redrawn in main window (temp fix for bug #23848) */
1363                         if (rect.xmin < rect.xmax && rect.ymin < rect.ymax)
1364                                 ui_draw_but(C, ar, &style, but, &rect);
1365                 }
1366         }
1367         
1368         /* restore matrix */
1369         glMatrixMode(GL_PROJECTION);
1370         glPopMatrix();
1371         glMatrixMode(GL_MODELVIEW);
1372         glPopMatrix();
1373
1374         if (multisample_enabled)
1375                 glEnable(GL_MULTISAMPLE_ARB);
1376         
1377         ui_draw_links(block);
1378 }
1379
1380 /* ************* EVENTS ************* */
1381
1382 /**
1383  * Check if the button is pushed, this is only meaningful for some button types.
1384  *
1385  * \return (0 == UNSELECT), (1 == SELECT), (-1 == DO-NOTHING)
1386  */
1387 int ui_is_but_push_ex(uiBut *but, double *value)
1388 {
1389         int is_push = 0;
1390
1391         if (but->bit) {
1392                 const bool state = ELEM(but->type, TOGN, ICONTOGN, OPTIONN) ? false : true;
1393                 int lvalue;
1394                 UI_GET_BUT_VALUE_INIT(but, *value);
1395                 lvalue = (int)*value;
1396                 if (UI_BITBUT_TEST(lvalue, (but->bitnr))) {
1397                         is_push = state;
1398                 }
1399                 else {
1400                         is_push = !state;
1401                 }
1402         }
1403         else {
1404                 switch (but->type) {
1405                         case BUT:
1406                         case HOTKEYEVT:
1407                         case KEYEVT:
1408                         case COLOR:
1409                                 is_push = -1;
1410                                 break;
1411                         case TOGBUT:
1412                         case TOG:
1413                         case ICONTOG:
1414                         case OPTION:
1415                                 UI_GET_BUT_VALUE_INIT(but, *value);
1416                                 if (*value != (double)but->hardmin) is_push = true;
1417                                 break;
1418                         case ICONTOGN:
1419                         case TOGN:
1420                         case OPTIONN:
1421                                 UI_GET_BUT_VALUE_INIT(but, *value);
1422                                 if (*value == 0.0) is_push = true;
1423                                 break;
1424                         case ROW:
1425                         case LISTROW:
1426                                 UI_GET_BUT_VALUE_INIT(but, *value);
1427                                 /* support for rna enum buts */
1428                                 if (but->rnaprop && (RNA_property_flag(but->rnaprop) & PROP_ENUM_FLAG)) {
1429                                         if ((int)*value & (int)but->hardmax) is_push = true;
1430                                 }
1431                                 else {
1432                                         if (*value == (double)but->hardmax) is_push = true;
1433                                 }
1434                                 break;
1435                         default:
1436                                 is_push = -1;
1437                                 break;
1438                 }
1439         }
1440
1441         return is_push;
1442 }
1443 int ui_is_but_push(uiBut *but)
1444 {
1445         double value = UI_BUT_VALUE_UNSET;
1446         return ui_is_but_push_ex(but, &value);
1447 }
1448
1449 static void ui_check_but_select(uiBut *but, double *value)
1450 {
1451         switch (ui_is_but_push_ex(but, value)) {
1452                 case true:
1453                         but->flag |= UI_SELECT;
1454                         break;
1455                 case false:
1456                         but->flag &= ~UI_SELECT;
1457                         break;
1458         }
1459 }
1460
1461 static uiBut *ui_find_inlink(uiBlock *block, void *poin)
1462 {
1463         uiBut *but;
1464         
1465         but = block->buttons.first;
1466         while (but) {
1467                 if (but->type == INLINK) {
1468                         if (but->poin == poin) return but;
1469                 }
1470                 but = but->next;
1471         }
1472         return NULL;
1473 }
1474
1475 static void ui_add_link_line(ListBase *listb, uiBut *but, uiBut *bt, short deactive)
1476 {
1477         uiLinkLine *line;
1478         
1479         line = MEM_callocN(sizeof(uiLinkLine), "linkline");
1480         BLI_addtail(listb, line);
1481         line->from = but;
1482         line->to = bt;
1483         line->deactive = deactive;
1484 }
1485
1486 uiBut *uiFindInlink(uiBlock *block, void *poin)
1487 {
1488         return ui_find_inlink(block, poin);
1489 }
1490
1491 void uiComposeLinks(uiBlock *block)
1492 {
1493         uiBut *but, *bt;
1494         uiLink *link;
1495         void ***ppoin;
1496         int a;
1497         
1498         but = block->buttons.first;
1499         while (but) {
1500                 if (but->type == LINK) {
1501                         link = but->link;
1502                         
1503                         /* for all pointers in the array */
1504                         if (link) {
1505                                 if (link->ppoin) {
1506                                         ppoin = link->ppoin;
1507                                         for (a = 0; a < *(link->totlink); a++) {
1508                                                 bt = ui_find_inlink(block, (*ppoin)[a]);
1509                                                 if (bt) {
1510                                                         if ((but->flag & UI_BUT_SCA_LINK_GREY) || (bt->flag & UI_BUT_SCA_LINK_GREY)) {
1511                                                                 ui_add_link_line(&link->lines, but, bt, true);
1512                                                         }
1513                                                         else {
1514                                                                 ui_add_link_line(&link->lines, but, bt, false);
1515                                                         }
1516
1517                                                 }
1518                                         }
1519                                 }
1520                                 else if (link->poin) {
1521                                         bt = ui_find_inlink(block, *link->poin);
1522                                         if (bt) {
1523                                                 if ((but->flag & UI_BUT_SCA_LINK_GREY) || (bt->flag & UI_BUT_SCA_LINK_GREY)) {
1524                                                         ui_add_link_line(&link->lines, but, bt, true);
1525                                                 }
1526                                                 else {
1527                                                         ui_add_link_line(&link->lines, but, bt, false);
1528                                                 }
1529                                         }
1530                                 }
1531                         }
1532                 }
1533                 but = but->next;
1534         }
1535 }
1536
1537
1538 /* ************************************************ */
1539
1540 void uiBlockSetButLock(uiBlock *block, bool val, const char *lockstr)
1541 {
1542         if (val) {
1543                 block->lock = val;
1544                 block->lockstr = lockstr;
1545         }
1546 }
1547
1548 void uiBlockClearButLock(uiBlock *block)
1549 {
1550         block->lock = false;
1551         block->lockstr = NULL;
1552 }
1553
1554 /* *************************************************************** */
1555
1556 void ui_delete_linkline(uiLinkLine *line, uiBut *but)
1557 {
1558         uiLink *link;
1559         int a, b;
1560         
1561         BLI_remlink(&but->link->lines, line);
1562
1563         link = line->from->link;
1564
1565         /* are there more pointers allowed? */
1566         if (link->ppoin) {
1567                 
1568                 if (*(link->totlink) == 1) {
1569                         *(link->totlink) = 0;
1570                         MEM_freeN(*(link->ppoin));
1571                         *(link->ppoin) = NULL;
1572                 }
1573                 else {
1574                         b = 0;
1575                         for (a = 0; a < (*(link->totlink)); a++) {
1576                                 if ((*(link->ppoin))[a] != line->to->poin) {
1577                                         (*(link->ppoin))[b] = (*(link->ppoin))[a];
1578                                         b++;
1579                                 }
1580                         }
1581                         (*(link->totlink))--;
1582                 }
1583         }
1584         else {
1585                 *(link->poin) = NULL;
1586         }
1587
1588         MEM_freeN(line);
1589         //REDRAW
1590 }
1591
1592 /* *********************** data get/set ***********************
1593  * this either works with the pointed to data, or can work with
1594  * an edit override pointer while dragging for example */
1595
1596 /* for buttons pointing to color for example */
1597 void ui_get_but_vectorf(uiBut *but, float vec[3])
1598 {
1599         PropertyRNA *prop;
1600         int a;
1601
1602         if (but->editvec) {
1603                 copy_v3_v3(vec, but->editvec);
1604         }
1605
1606         if (but->rnaprop) {
1607                 prop = but->rnaprop;
1608
1609                 zero_v3(vec);
1610
1611                 if (RNA_property_type(prop) == PROP_FLOAT) {
1612                         int tot = RNA_property_array_length(&but->rnapoin, prop);
1613                         BLI_assert(tot > 0);
1614                         if (tot == 3) {
1615                                 RNA_property_float_get_array(&but->rnapoin, prop, vec);
1616                         }
1617                         else {
1618                                 tot = min_ii(tot, 3);
1619                                 for (a = 0; a < tot; a++) {
1620                                         vec[a] = RNA_property_float_get_index(&but->rnapoin, prop, a);
1621                                 }
1622                         }
1623                 }
1624         }
1625         else if (but->pointype == UI_BUT_POIN_CHAR) {
1626                 const char *cp = (char *)but->poin;
1627
1628                 vec[0] = ((float)cp[0]) / 255.0f;
1629                 vec[1] = ((float)cp[1]) / 255.0f;
1630                 vec[2] = ((float)cp[2]) / 255.0f;
1631         }
1632         else if (but->pointype == UI_BUT_POIN_FLOAT) {
1633                 const float *fp = (float *)but->poin;
1634                 copy_v3_v3(vec, fp);
1635         }
1636         else {
1637                 if (but->editvec == NULL) {
1638                         fprintf(stderr, "%s: can't get color, should never happen\n", __func__);
1639                         zero_v3(vec);
1640                 }
1641         }
1642
1643         if (but->type == BUT_NORMAL) {
1644                 normalize_v3(vec);
1645         }
1646 }
1647
1648 /* for buttons pointing to color for example */
1649 void ui_set_but_vectorf(uiBut *but, const float vec[3])
1650 {
1651         PropertyRNA *prop;
1652
1653         if (but->editvec) {
1654                 copy_v3_v3(but->editvec, vec);
1655         }
1656
1657         if (but->rnaprop) {
1658                 prop = but->rnaprop;
1659
1660                 if (RNA_property_type(prop) == PROP_FLOAT) {
1661                         int tot;
1662                         int a;
1663
1664                         tot = RNA_property_array_length(&but->rnapoin, prop);
1665                         BLI_assert(tot > 0);
1666                         if (tot == 3) {
1667                                 RNA_property_float_set_array(&but->rnapoin, prop, vec);
1668                         }
1669                         else {
1670                                 tot = min_ii(tot, 3);
1671                                 for (a = 0; a < tot; a++) {
1672                                         RNA_property_float_set_index(&but->rnapoin, prop, a, vec[a]);
1673                                 }
1674                         }
1675                 }
1676         }
1677         else if (but->pointype == UI_BUT_POIN_CHAR) {
1678                 char *cp = (char *)but->poin;
1679                 cp[0] = (char)(0.5f + vec[0] * 255.0f);
1680                 cp[1] = (char)(0.5f + vec[1] * 255.0f);
1681                 cp[2] = (char)(0.5f + vec[2] * 255.0f);
1682         }
1683         else if (but->pointype == UI_BUT_POIN_FLOAT) {
1684                 float *fp = (float *)but->poin;
1685                 copy_v3_v3(fp, vec);
1686         }
1687 }
1688
1689 bool ui_is_but_float(const uiBut *but)
1690 {
1691         if (but->pointype == UI_BUT_POIN_FLOAT && but->poin)
1692                 return true;
1693         
1694         if (but->rnaprop && RNA_property_type(but->rnaprop) == PROP_FLOAT)
1695                 return true;
1696         
1697         return false;
1698 }
1699
1700 bool ui_is_but_bool(const uiBut *but)
1701 {
1702         if (ELEM(but->type, TOG, TOGN, ICONTOG, ICONTOGN))
1703                 return true;
1704
1705         if (but->rnaprop && RNA_property_type(but->rnaprop) == PROP_BOOLEAN)
1706                 return true;
1707
1708         return false;
1709 }
1710
1711
1712 bool ui_is_but_unit(const uiBut *but)
1713 {
1714         UnitSettings *unit = but->block->unit;
1715         const int unit_type = uiButGetUnitType(but);
1716
1717         if (unit_type == PROP_UNIT_NONE)
1718                 return false;
1719
1720 #if 1 /* removed so angle buttons get correct snapping */
1721         if (ui_is_but_unit_radians_ex(unit, unit_type))
1722                 return false;
1723 #endif
1724         
1725         /* for now disable time unit conversion */
1726         if (unit_type == PROP_UNIT_TIME)
1727                 return false;
1728
1729         if (unit->system == USER_UNIT_NONE) {
1730                 if (unit_type != PROP_UNIT_ROTATION) {
1731                         return false;
1732                 }
1733         }
1734
1735         return true;
1736 }
1737
1738 /**
1739  * Check if this button is similar enough to be grouped with another.
1740  */
1741 bool ui_is_but_compatible(const uiBut *but_a, const uiBut *but_b)
1742 {
1743         if (but_a->type != but_b->type)
1744                 return false;
1745         if (but_a->pointype != but_b->pointype)
1746                 return false;
1747
1748         if (but_a->rnaprop) {
1749                 /* skip 'rnapoin.data', 'rnapoin.id.data'
1750                  * allow different data to have the same props edited at once */
1751                 if (but_a->rnapoin.type != but_b->rnapoin.type)
1752                         return false;
1753                 if (RNA_property_type(but_a->rnaprop) != RNA_property_type(but_b->rnaprop))
1754                         return false;
1755                 if (RNA_property_subtype(but_a->rnaprop) != RNA_property_subtype(but_b->rnaprop))
1756                         return false;
1757         }
1758
1759         return true;
1760 }
1761
1762 bool ui_is_but_rna_valid(uiBut *but)
1763 {
1764         if (but->rnaprop == NULL || RNA_struct_contains_property(&but->rnapoin, but->rnaprop)) {
1765                 return true;
1766         }
1767         else {
1768                 printf("property removed %s: %p\n", but->drawstr, but->rnaprop);
1769                 return false;
1770         }
1771 }
1772
1773 double ui_get_but_val(uiBut *but)
1774 {
1775         PropertyRNA *prop;
1776         double value = 0.0;
1777
1778         if (but->editval) { return *(but->editval); }
1779         if (but->poin == NULL && but->rnapoin.data == NULL) return 0.0;
1780
1781         if (but->rnaprop) {
1782                 prop = but->rnaprop;
1783
1784                 BLI_assert(but->rnaindex != -1);
1785
1786                 switch (RNA_property_type(prop)) {
1787                         case PROP_BOOLEAN:
1788                                 if (RNA_property_array_check(prop))
1789                                         value = RNA_property_boolean_get_index(&but->rnapoin, prop, but->rnaindex);
1790                                 else
1791                                         value = RNA_property_boolean_get(&but->rnapoin, prop);
1792                                 break;
1793                         case PROP_INT:
1794                                 if (RNA_property_array_check(prop))
1795                                         value = RNA_property_int_get_index(&but->rnapoin, prop, but->rnaindex);
1796                                 else
1797                                         value = RNA_property_int_get(&but->rnapoin, prop);
1798                                 break;
1799                         case PROP_FLOAT:
1800                                 if (RNA_property_array_check(prop))
1801                                         value = RNA_property_float_get_index(&but->rnapoin, prop, but->rnaindex);
1802                                 else
1803                                         value = RNA_property_float_get(&but->rnapoin, prop);
1804                                 break;
1805                         case PROP_ENUM:
1806                                 value = RNA_property_enum_get(&but->rnapoin, prop);
1807                                 break;
1808                         default:
1809                                 value = 0.0;
1810                                 break;
1811                 }
1812         }
1813         else if (but->pointype == UI_BUT_POIN_CHAR) {
1814                 value = *(char *)but->poin;
1815         }
1816         else if (but->pointype == UI_BUT_POIN_SHORT) {
1817                 value = *(short *)but->poin;
1818         }
1819         else if (but->pointype == UI_BUT_POIN_INT) {
1820                 value = *(int *)but->poin;
1821         }
1822         else if (but->pointype == UI_BUT_POIN_FLOAT) {
1823                 value = *(float *)but->poin;
1824         }
1825
1826         return value;
1827 }
1828
1829 void ui_set_but_val(uiBut *but, double value)
1830 {
1831         PropertyRNA *prop;
1832
1833         /* value is a hsv value: convert to rgb */
1834         if (but->rnaprop) {
1835                 prop = but->rnaprop;
1836
1837                 if (RNA_property_editable(&but->rnapoin, prop)) {
1838                         switch (RNA_property_type(prop)) {
1839                                 case PROP_BOOLEAN:
1840                                         if (RNA_property_array_check(prop))
1841                                                 RNA_property_boolean_set_index(&but->rnapoin, prop, but->rnaindex, value);
1842                                         else
1843                                                 RNA_property_boolean_set(&but->rnapoin, prop, value);
1844                                         break;
1845                                 case PROP_INT:
1846                                         if (RNA_property_array_check(prop))
1847                                                 RNA_property_int_set_index(&but->rnapoin, prop, but->rnaindex, (int)value);
1848                                         else
1849                                                 RNA_property_int_set(&but->rnapoin, prop, (int)value);
1850                                         break;
1851                                 case PROP_FLOAT:
1852                                         if (RNA_property_array_check(prop))
1853                                                 RNA_property_float_set_index(&but->rnapoin, prop, but->rnaindex, value);
1854                                         else
1855                                                 RNA_property_float_set(&but->rnapoin, prop, value);
1856                                         break;
1857                                 case PROP_ENUM:
1858                                         if (RNA_property_flag(prop) & PROP_ENUM_FLAG) {
1859                                                 int ivalue = (int)value;
1860                                                 ivalue ^= RNA_property_enum_get(&but->rnapoin, prop); /* toggle for enum/flag buttons */
1861                                                 RNA_property_enum_set(&but->rnapoin, prop, ivalue);
1862                                         }
1863                                         else {
1864                                                 RNA_property_enum_set(&but->rnapoin, prop, value);
1865                                         }
1866                                         break;
1867                                 default:
1868                                         break;
1869                         }
1870                 }
1871
1872                 /* we can't be sure what RNA set functions actually do,
1873                  * so leave this unset */
1874                 value = UI_BUT_VALUE_UNSET;
1875         }
1876         else if (but->pointype == 0) {
1877                 /* pass */
1878         }
1879         else {
1880                 /* first do rounding */
1881                 if (but->pointype == UI_BUT_POIN_CHAR) {
1882                         value = (char)floor(value + 0.5);
1883                 }
1884                 else if (but->pointype == UI_BUT_POIN_SHORT) {
1885                         value = (short)floor(value + 0.5);
1886                 }
1887                 else if (but->pointype == UI_BUT_POIN_INT)
1888                         value = (int)floor(value + 0.5);
1889                 else if (but->pointype == UI_BUT_POIN_FLOAT) {
1890                         float fval = (float)value;
1891                         if (fval >= -0.00001f && fval <= 0.00001f) fval = 0.0f;  /* prevent negative zero */
1892                         value = fval;
1893                 }
1894                 
1895                 /* then set value with possible edit override */
1896                 if (but->editval)
1897                         value = *but->editval = value;
1898                 else if (but->pointype == UI_BUT_POIN_CHAR)
1899                         value = *((char *)but->poin) = (char)value;
1900                 else if (but->pointype == UI_BUT_POIN_SHORT)
1901                         value = *((short *)but->poin) = (short)value;
1902                 else if (but->pointype == UI_BUT_POIN_INT)
1903                         value = *((int *)but->poin) = (int)value;
1904                 else if (but->pointype == UI_BUT_POIN_FLOAT)
1905                         value = *((float *)but->poin) = (float)value;
1906         }
1907
1908         ui_check_but_select(but, &value);
1909 }
1910
1911 int ui_get_but_string_max_length(uiBut *but)
1912 {
1913         if (ELEM(but->type, TEX, SEARCH_MENU, SEARCH_MENU_UNLINK))
1914                 return but->hardmax;
1915         else
1916                 return UI_MAX_DRAW_STR;
1917 }
1918
1919 uiBut *ui_get_but_drag_multi_edit(uiBut *but)
1920 {
1921         uiBut *but_iter;
1922
1923         BLI_assert(but->flag & UI_BUT_DRAG_MULTI);
1924
1925         for (but_iter = but->block->buttons.first; but_iter; but_iter = but_iter->next) {
1926                 if (but_iter->editstr) {
1927                         break;
1928                 }
1929         }
1930
1931         return but_iter;
1932 }
1933
1934 static double ui_get_but_scale_unit(uiBut *but, double value)
1935 {
1936         UnitSettings *unit = but->block->unit;
1937         int unit_type = uiButGetUnitType(but);
1938
1939         /* Time unit is a bit special, not handled by BKE_scene_unit_scale() for now. */
1940         if (unit_type == PROP_UNIT_TIME) { /* WARNING - using evil_C :| */
1941                 Scene *scene = CTX_data_scene(but->block->evil_C);
1942                 return FRA2TIME(value);
1943         }
1944         else {
1945                 return BKE_scene_unit_scale(unit, RNA_SUBTYPE_UNIT_VALUE(unit_type), value);
1946         }
1947 }
1948
1949 /* str will be overwritten */
1950 void ui_convert_to_unit_alt_name(uiBut *but, char *str, size_t maxlen)
1951 {
1952         if (ui_is_but_unit(but)) {
1953                 UnitSettings *unit = but->block->unit;
1954                 int unit_type = uiButGetUnitType(but);
1955                 char *orig_str;
1956                 
1957                 orig_str = BLI_strdup(str);
1958                 
1959                 bUnit_ToUnitAltName(str, maxlen, orig_str, unit->system, RNA_SUBTYPE_UNIT_VALUE(unit_type));
1960                 
1961                 MEM_freeN(orig_str);
1962         }
1963 }
1964
1965 /**
1966  * \param float_precision  Override the button precision.
1967  */
1968 static void ui_get_but_string_unit(uiBut *but, char *str, int len_max, double value, bool pad, int float_precision)
1969 {
1970         UnitSettings *unit = but->block->unit;
1971         const bool do_split = (unit->flag & USER_UNIT_OPT_SPLIT) != 0;
1972         int unit_type = uiButGetUnitType(but);
1973         int precision;
1974
1975         if (unit->scale_length < 0.0001f) unit->scale_length = 1.0f;  // XXX do_versions
1976
1977         /* Use precision override? */
1978         if (float_precision == -1) {
1979                 /* Sanity checks */
1980                 precision = (int)but->a2;
1981                 if      (precision > UI_PRECISION_FLOAT_MAX) precision = UI_PRECISION_FLOAT_MAX;
1982                 else if (precision == -1)                    precision = 2;
1983         }
1984         else {
1985                 precision = float_precision;
1986         }
1987
1988         bUnit_AsString(str, len_max, ui_get_but_scale_unit(but, value), precision,
1989                        unit->system, RNA_SUBTYPE_UNIT_VALUE(unit_type), do_split, pad);
1990 }
1991
1992 static float ui_get_but_step_unit(uiBut *but, float step_default)
1993 {
1994         int unit_type = RNA_SUBTYPE_UNIT_VALUE(uiButGetUnitType(but));
1995         double step;
1996
1997         step = bUnit_ClosestScalar(ui_get_but_scale_unit(but, step_default), but->block->unit->system, unit_type);
1998
1999         /* -1 is an error value */
2000         if (step != -1.0) {
2001                 BLI_assert(step > 0.0);
2002                 return (float)(step / ui_get_but_scale_unit(but, 1.0)) * 100.0f;
2003         }
2004         else {
2005                 return step_default;
2006         }
2007 }
2008
2009 /**
2010  * \param float_precision  For number buttons the precision to use or -1 to fallback to the button default.
2011  */
2012 void ui_get_but_string_ex(uiBut *but, char *str, const size_t maxlen, const int float_precision)
2013 {
2014         if (but->rnaprop && ELEM(but->type, TEX, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
2015                 PropertyType type;
2016                 const char *buf = NULL;
2017                 int buf_len;
2018
2019                 type = RNA_property_type(but->rnaprop);
2020
2021                 if (type == PROP_STRING) {
2022                         /* RNA string */
2023                         buf = RNA_property_string_get_alloc(&but->rnapoin, but->rnaprop, str, maxlen, &buf_len);
2024                 }
2025                 else if (type == PROP_ENUM) {
2026                         /* RNA enum */
2027                         int value = RNA_property_enum_get(&but->rnapoin, but->rnaprop);
2028                         if (RNA_property_enum_name(but->block->evil_C, &but->rnapoin, but->rnaprop, value, &buf)) {
2029                                 BLI_strncpy(str, buf, maxlen);
2030                                 buf = str;
2031                         }
2032                 }
2033                 else if (type == PROP_POINTER) {
2034                         /* RNA pointer */
2035                         PointerRNA ptr = RNA_property_pointer_get(&but->rnapoin, but->rnaprop);
2036                         buf = RNA_struct_name_get_alloc(&ptr, str, maxlen, &buf_len);
2037                 }
2038                 else {
2039                         BLI_assert(0);
2040                 }
2041
2042                 if (!buf) {
2043                         str[0] = '\0';
2044                 }
2045                 else if (buf && buf != str) {
2046                         /* string was too long, we have to truncate */
2047                         memcpy(str, buf, MIN2(maxlen, (size_t)(buf_len + 1)));
2048                         MEM_freeN((void *)buf);
2049                 }
2050         }
2051         else if (but->type == TEX) {
2052                 /* string */
2053                 BLI_strncpy(str, but->poin, maxlen);
2054                 return;
2055         }
2056         else if (ELEM(but->type, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
2057                 /* string */
2058                 BLI_strncpy(str, but->poin, maxlen);
2059                 return;
2060         }
2061         else if (ui_but_anim_expression_get(but, str, maxlen)) {
2062                 /* driver expression */
2063         }
2064         else {
2065                 /* number editing */
2066                 double value;
2067
2068                 value = ui_get_but_val(but);
2069
2070                 if (ui_is_but_float(but)) {
2071                         if (ui_is_but_unit(but)) {
2072                                 ui_get_but_string_unit(but, str, maxlen, value, false, float_precision);
2073                         }
2074                         else {
2075                                 const int prec = (float_precision == -1) ? ui_but_float_precision(but, value) : float_precision;
2076                                 BLI_snprintf(str, maxlen, "%.*f", prec, value);
2077                         }
2078                 }
2079                 else
2080                         BLI_snprintf(str, maxlen, "%d", (int)value);
2081         }
2082 }
2083 void ui_get_but_string(uiBut *but, char *str, const size_t maxlen)
2084 {
2085         ui_get_but_string_ex(but, str, maxlen, -1);
2086 }
2087
2088 #ifdef WITH_PYTHON
2089
2090 static bool ui_set_but_string_eval_num_unit(bContext *C, uiBut *but, const char *str, double *value)
2091 {
2092         char str_unit_convert[256];
2093         const int unit_type = uiButGetUnitType(but);
2094
2095         BLI_strncpy(str_unit_convert, str, sizeof(str_unit_convert));
2096
2097         /* ugly, use the draw string to get the value,
2098          * this could cause problems if it includes some text which resolves to a unit */
2099         bUnit_ReplaceString(str_unit_convert, sizeof(str_unit_convert), but->drawstr,
2100                             ui_get_but_scale_unit(but, 1.0), but->block->unit->system, RNA_SUBTYPE_UNIT_VALUE(unit_type));
2101
2102         return (BPY_button_exec(C, str_unit_convert, value, true) != -1);
2103 }
2104
2105 #endif /* WITH_PYTHON */
2106
2107
2108 bool ui_set_but_string_eval_num(bContext *C, uiBut *but, const char *str, double *value)
2109 {
2110         bool ok = false;
2111
2112 #ifdef WITH_PYTHON
2113
2114         if (str[0] != '\0') {
2115                 bool is_unit_but = (ui_is_but_float(but) && ui_is_but_unit(but));
2116                 /* only enable verbose if we won't run again with units */
2117                 if (BPY_button_exec(C, str, value, is_unit_but == false) != -1) {
2118                         /* if the value parsed ok without unit conversion this button may still need a unit multiplier */
2119                         if (is_unit_but) {
2120                                 char str_new[128];
2121
2122                                 BLI_snprintf(str_new, sizeof(str_new), "%f", *value);
2123                                 ok = ui_set_but_string_eval_num_unit(C, but, str_new, value);
2124                         }
2125                         else {
2126                                 ok = true; /* parse normal string via py (no unit conversion needed) */
2127                         }
2128                 }
2129                 else if (is_unit_but) {
2130                         /* parse failed, this is a unit but so run replacements and parse again */
2131                         ok = ui_set_but_string_eval_num_unit(C, but, str, value);
2132                 }
2133         }
2134
2135 #else /* WITH_PYTHON */
2136
2137         *value = atof(str);
2138         ok = true;
2139
2140         (void)C;
2141         (void)but;
2142
2143 #endif /* WITH_PYTHON */
2144
2145         return ok;
2146 }
2147
2148
2149 bool ui_set_but_string(bContext *C, uiBut *but, const char *str)
2150 {
2151         if (but->rnaprop && ELEM(but->type, TEX, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
2152                 if (RNA_property_editable(&but->rnapoin, but->rnaprop)) {
2153                         PropertyType type;
2154
2155                         type = RNA_property_type(but->rnaprop);
2156
2157                         if (type == PROP_STRING) {
2158                                 /* RNA string */
2159                                 RNA_property_string_set(&but->rnapoin, but->rnaprop, str);
2160                                 return true;
2161                         }
2162                         else if (type == PROP_POINTER) {
2163                                 /* RNA pointer */
2164                                 PointerRNA ptr, rptr;
2165                                 PropertyRNA *prop;
2166
2167                                 if (str[0] == '\0') {
2168                                         RNA_property_pointer_set(&but->rnapoin, but->rnaprop, PointerRNA_NULL);
2169                                         return true;
2170                                 }
2171                                 else {
2172                                         ptr = but->rnasearchpoin;
2173                                         prop = but->rnasearchprop;
2174                                         
2175                                         if (prop && RNA_property_collection_lookup_string(&ptr, prop, str, &rptr))
2176                                                 RNA_property_pointer_set(&but->rnapoin, but->rnaprop, rptr);
2177
2178                                         return true;
2179                                 }
2180
2181                                 return false;
2182                         }
2183                         else if (type == PROP_ENUM) {
2184                                 int value;
2185                                 if (RNA_property_enum_value(but->block->evil_C, &but->rnapoin, but->rnaprop, str, &value)) {
2186                                         RNA_property_enum_set(&but->rnapoin, but->rnaprop, value);
2187                                         return true;
2188                                 }
2189                                 return false;
2190                         }
2191                         else {
2192                                 BLI_assert(0);
2193                         }
2194                 }
2195         }
2196         else if (but->type == TEX) {
2197                 /* string */
2198                 if (ui_is_but_utf8(but)) BLI_strncpy_utf8(but->poin, str, but->hardmax);
2199                 else BLI_strncpy(but->poin, str, but->hardmax);
2200
2201                 return true;
2202         }
2203         else if (ELEM(but->type, SEARCH_MENU, SEARCH_MENU_UNLINK)) {
2204                 /* string */
2205                 BLI_strncpy(but->poin, str, but->hardmax);
2206                 return true;
2207         }
2208         else if (ui_but_anim_expression_set(but, str)) {
2209                 /* driver expression */
2210                 return true;
2211         }
2212         else if (str[0] == '#') {
2213                 /* shortcut to create new driver expression (versus immediate Py-execution) */
2214                 return ui_but_anim_expression_create(but, str + 1);
2215         }
2216         else {
2217                 /* number editing */
2218                 double value;
2219
2220                 if (ui_set_but_string_eval_num(C, but, str, &value) == false) {
2221                         return false;
2222                 }
2223
2224                 if (!ui_is_but_float(but)) value = (int)floor(value + 0.5);
2225
2226                 /* not that we use hard limits here */
2227                 if (value < (double)but->hardmin) value = but->hardmin;
2228                 if (value > (double)but->hardmax) value = but->hardmax;
2229
2230                 ui_set_but_val(but, value);
2231                 return true;
2232         }
2233
2234         return false;
2235 }
2236
2237 void ui_set_but_default(bContext *C, const bool all, const bool use_afterfunc)
2238 {
2239         const char *opstring = "UI_OT_reset_default_button";
2240
2241         if (use_afterfunc) {
2242                 PointerRNA *ptr;
2243                 wmOperatorType *ot = WM_operatortype_find(opstring, 0);
2244                 ptr = ui_handle_afterfunc_add_operator(ot, WM_OP_EXEC_DEFAULT, true);
2245                 RNA_boolean_set(ptr, "all", all);
2246         }
2247         else {
2248                 PointerRNA ptr;
2249                 WM_operator_properties_create(&ptr, opstring);
2250                 RNA_boolean_set(&ptr, "all", all);
2251                 WM_operator_name_call(C, opstring, WM_OP_EXEC_DEFAULT, &ptr);
2252                 WM_operator_properties_free(&ptr);
2253         }
2254 }
2255
2256 static double soft_range_round_up(double value, double max)
2257 {
2258         /* round up to .., 0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50, ..
2259          * checking for 0.0 prevents floating point exceptions */
2260         double newmax = (value != 0.0) ? pow(10.0, ceil(log(value) / M_LN10)) : 0.0;
2261
2262         if (newmax * 0.2 >= max && newmax * 0.2 >= value)
2263                 return newmax * 0.2;
2264         else if (newmax * 0.5 >= max && newmax * 0.5 >= value)
2265                 return newmax * 0.5;
2266         else
2267                 return newmax;
2268 }
2269
2270 static double soft_range_round_down(double value, double max)
2271 {
2272         /* round down to .., 0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50, ..
2273          * checking for 0.0 prevents floating point exceptions */
2274         double newmax = (value != 0.0) ? pow(10.0, floor(log(value) / M_LN10)) : 0.0;
2275
2276         if (newmax * 5.0 <= max && newmax * 5.0 <= value)
2277                 return newmax * 5.0;
2278         else if (newmax * 2.0 <= max && newmax * 2.0 <= value)
2279                 return newmax * 2.0;
2280         else
2281                 return newmax;
2282 }
2283
2284 /* note: this could be split up into functions which handle arrays and not */
2285 static void ui_set_but_soft_range(uiBut *but)
2286 {
2287         /* ideally we would not limit this but practically, its more than
2288          * enough worst case is very long vectors wont use a smart soft-range
2289          * which isn't so bad. */
2290
2291         if (but->rnaprop) {
2292                 const PropertyType type = RNA_property_type(but->rnaprop);
2293                 double softmin, softmax /*, step, precision*/;
2294                 double value_min;
2295                 double value_max;
2296
2297                 /* clamp button range to something reasonable in case
2298                  * we get -inf/inf from RNA properties */
2299                 if (type == PROP_INT) {
2300                         const bool is_array = RNA_property_array_check(but->rnaprop);
2301                         int imin, imax, istep;
2302
2303                         RNA_property_int_ui_range(&but->rnapoin, but->rnaprop, &imin, &imax, &istep);
2304                         softmin = (imin == INT_MIN) ? -1e4 : imin;
2305                         softmax = (imin == INT_MAX) ? 1e4 : imax;
2306                         /*step = istep;*/ /*UNUSED*/
2307                         /*precision = 1;*/ /*UNUSED*/
2308
2309                         if (is_array) {
2310                                 int value_range[2];
2311                                 RNA_property_int_get_array_range(&but->rnapoin, but->rnaprop, value_range);
2312                                 value_min = (double)value_range[0];
2313                                 value_max = (double)value_range[1];
2314                         }
2315                         else {
2316                                 value_min = value_max = (double)RNA_property_int_get(&but->rnapoin, but->rnaprop);
2317                         }
2318                 }
2319                 else if (type == PROP_FLOAT) {
2320                         const bool is_array = RNA_property_array_check(but->rnaprop);
2321                         float fmin, fmax, fstep, fprecision;
2322
2323                         RNA_property_float_ui_range(&but->rnapoin, but->rnaprop, &fmin, &fmax, &fstep, &fprecision);
2324                         softmin = (fmin == -FLT_MAX) ? (float)-1e4 : fmin;
2325                         softmax = (fmax == FLT_MAX) ? (float)1e4 : fmax;
2326                         /*step = fstep;*/ /*UNUSED*/
2327                         /*precision = fprecision;*/ /*UNUSED*/
2328
2329                         if (is_array) {
2330                                 float value_range[2];
2331                                 RNA_property_float_get_array_range(&but->rnapoin, but->rnaprop, value_range);
2332                                 value_min = (double)value_range[0];
2333                                 value_max = (double)value_range[1];
2334                         }
2335                         else {
2336                                 value_min = value_max = (double)RNA_property_float_get(&but->rnapoin, but->rnaprop);
2337                         }
2338                 }
2339                 else {
2340                         return;
2341                 }
2342
2343                 /* if the value goes out of the soft/max range, adapt the range */
2344                 if (value_min + 1e-10 < softmin) {
2345                         if (value_min < 0.0)
2346                                 softmin = -soft_range_round_up(-value_min, -softmin);
2347                         else
2348                                 softmin = soft_range_round_down(value_min, softmin);
2349
2350                         if (softmin < (double)but->hardmin)
2351                                 softmin = (double)but->hardmin;
2352                 }
2353                 if (value_max - 1e-10 > softmax) {
2354                         if (value_max < 0.0)
2355                                 softmax = -soft_range_round_down(-value_max, -softmax);
2356                         else
2357                                 softmax = soft_range_round_up(value_max, softmax);
2358
2359                         if (softmax > (double)but->hardmax)
2360                                 softmax = but->hardmax;
2361                 }
2362
2363                 but->softmin = softmin;
2364                 but->softmax = softmax;
2365         }
2366         else if (but->poin && (but->pointype & UI_BUT_POIN_TYPES)) {
2367                 float value = ui_get_but_val(but);
2368                 CLAMP(value, but->hardmin, but->hardmax);
2369                 but->softmin = min_ff(but->softmin, value);
2370                 but->softmax = max_ff(but->softmax, value);
2371         }
2372         else {
2373                 BLI_assert(0);
2374         }
2375 }
2376
2377 /* ******************* Free ********************/
2378
2379 static void ui_free_link(uiLink *link)
2380 {
2381         if (link) {
2382                 BLI_freelistN(&link->lines);
2383                 MEM_freeN(link);
2384         }
2385 }
2386
2387 /* can be called with C==NULL */
2388 static void ui_free_but(const bContext *C, uiBut *but)
2389 {
2390         if (but->opptr) {
2391                 WM_operator_properties_free(but->opptr);
2392                 MEM_freeN(but->opptr);
2393         }
2394
2395         if (but->func_argN) {
2396                 MEM_freeN(but->func_argN);
2397         }
2398
2399         if (but->active) {
2400                 /* XXX solve later, buttons should be free-able without context ideally,
2401                  * however they may have open tooltips or popup windows, which need to
2402                  * be closed using a context pointer */
2403                 if (C) {
2404                         ui_button_active_free(C, but);
2405                 }
2406                 else {
2407                         if (but->active) {
2408                                 MEM_freeN(but->active);
2409                         }
2410                 }
2411         }
2412         if (but->str && but->str != but->strdata) {
2413                 MEM_freeN(but->str);
2414         }
2415         ui_free_link(but->link);
2416
2417         if ((but->type == BUT_IMAGE) && but->poin) {
2418                 IMB_freeImBuf((struct ImBuf *)but->poin);
2419         }
2420
2421         BLI_assert(UI_butstore_is_registered(but->block, but) == false);
2422
2423         MEM_freeN(but);
2424 }
2425
2426 /* can be called with C==NULL */
2427 void uiFreeBlock(const bContext *C, uiBlock *block)
2428 {
2429         uiBut *but;
2430
2431         UI_butstore_clear(block);
2432
2433         while ((but = BLI_pophead(&block->buttons))) {
2434                 ui_free_but(C, but);
2435         }
2436
2437         if (block->unit) {
2438                 MEM_freeN(block->unit);
2439         }
2440
2441         if (block->func_argN) {
2442                 MEM_freeN(block->func_argN);
2443         }
2444
2445         CTX_store_free_list(&block->contexts);
2446
2447         BLI_freelistN(&block->saferct);
2448         BLI_freelistN(&block->color_pickers.list);
2449         
2450         MEM_freeN(block);
2451 }
2452
2453 /* can be called with C==NULL */
2454 void uiFreeBlocks(const bContext *C, ListBase *lb)
2455 {
2456         uiBlock *block;
2457         
2458         while ((block = BLI_pophead(lb))) {
2459                 uiFreeBlock(C, block);
2460         }
2461 }
2462
2463 void uiFreeInactiveBlocks(const bContext *C, ListBase *lb)
2464 {
2465         uiBlock *block, *nextblock;
2466
2467         for (block = lb->first; block; block = nextblock) {
2468                 nextblock = block->next;
2469         
2470                 if (!block->handle) {
2471                         if (!block->active) {
2472                                 BLI_remlink(lb, block);
2473                                 uiFreeBlock(C, block);
2474                         }
2475                         else
2476                                 block->active = 0;
2477                 }
2478         }
2479 }
2480
2481 void uiBlockSetRegion(uiBlock *block, ARegion *region)
2482 {
2483         ListBase *lb = &region->uiblocks;
2484         uiBlock *oldblock = NULL;
2485
2486         /* each listbase only has one block with this name, free block
2487          * if is already there so it can be rebuilt from scratch */
2488         if (lb) {
2489                 oldblock = BLI_findstring(lb, block->name, offsetof(uiBlock, name));
2490
2491                 if (oldblock) {
2492                         oldblock->active = 0;
2493                         oldblock->panel = NULL;
2494                         oldblock->handle = NULL;
2495                 }
2496
2497                 /* at the beginning of the list! for dynamical menus/blocks */
2498                 BLI_addhead(lb, block);
2499         }
2500
2501         block->oldblock = oldblock;
2502 }
2503
2504 uiBlock *uiBeginBlock(const bContext *C, ARegion *region, const char *name, short dt)
2505 {
2506         uiBlock *block;
2507         wmWindow *window;
2508         Scene *scn;
2509         int getsizex, getsizey;
2510
2511         window = CTX_wm_window(C);
2512         scn = CTX_data_scene(C);
2513
2514         block = MEM_callocN(sizeof(uiBlock), "uiBlock");
2515         block->active = 1;
2516         block->dt = dt;
2517         block->evil_C = (void *)C;  /* XXX */
2518
2519         if (scn) {
2520                 block->color_profile = true;
2521
2522                 /* store display device name, don't lookup for transformations yet
2523                  * block could be used for non-color displays where looking up for transformation
2524                  * would slow down redraw, so only lookup for actual transform when it's indeed
2525                  * needed
2526                  */
2527                 BLI_strncpy(block->display_device, scn->display_settings.display_device, sizeof(block->display_device));
2528
2529                 /* copy to avoid crash when scene gets deleted with ui still open */
2530                 block->unit = MEM_mallocN(sizeof(scn->unit), "UI UnitSettings");
2531                 memcpy(block->unit, &scn->unit, sizeof(scn->unit));
2532         }
2533
2534         BLI_strncpy(block->name, name, sizeof(block->name));
2535
2536         if (region)
2537                 uiBlockSetRegion(block, region);
2538
2539         /* window matrix and aspect */
2540         if (region && region->swinid) {
2541                 wm_subwindow_matrix_get(window, region->swinid, block->winmat);
2542                 wm_subwindow_size_get(window, region->swinid, &getsizex, &getsizey);
2543
2544                 block->aspect = 2.0f / fabsf(getsizex * block->winmat[0][0]);
2545         }
2546         else {
2547                 /* no subwindow created yet, for menus for example, so we
2548                  * use the main window instead, since buttons are created
2549                  * there anyway */
2550                 wm_subwindow_matrix_get(window, window->screen->mainwin, block->winmat);
2551                 wm_subwindow_size_get(window, window->screen->mainwin, &getsizex, &getsizey);
2552
2553                 block->aspect = 2.0f / fabsf(getsizex * block->winmat[0][0]);
2554                 block->auto_open = true;
2555                 block->flag |= UI_BLOCK_LOOP; /* tag as menu */
2556         }
2557
2558         return block;
2559 }
2560
2561 uiBlock *uiGetBlock(const char *name, ARegion *ar)
2562 {
2563         return BLI_findstring(&ar->uiblocks, name, offsetof(uiBlock, name));
2564 }
2565
2566 void uiBlockSetEmboss(uiBlock *block, char dt)
2567 {
2568         block->dt = dt;
2569 }
2570
2571 void ui_check_but(uiBut *but)
2572 {
2573         /* if something changed in the button */
2574         double value = UI_BUT_VALUE_UNSET;
2575 //      float okwidth; // UNUSED
2576         
2577         ui_check_but_select(but, &value);
2578         
2579         /* only update soft range while not editing */
2580         if (!(but->editval || but->editstr || but->editvec)) {
2581                 if ((but->rnaprop != NULL) ||
2582                     (but->poin && (but->pointype & UI_BUT_POIN_TYPES)))
2583                 {
2584                         ui_set_but_soft_range(but);
2585                 }
2586         }
2587
2588         /* test for min and max, icon sliders, etc */
2589         switch (but->type) {
2590                 case NUM:
2591                 case SCROLL:
2592                 case NUMSLI:
2593                         UI_GET_BUT_VALUE_INIT(but, value);
2594                         if (value < (double)but->hardmin) ui_set_but_val(but, but->hardmin);
2595                         else if (value > (double)but->hardmax) ui_set_but_val(but, but->hardmax);
2596                         break;
2597                         
2598                 case ICONTOG: 
2599                 case ICONTOGN:
2600                         if (!but->rnaprop || (RNA_property_flag(but->rnaprop) & PROP_ICONS_CONSECUTIVE)) {
2601                                 if (but->flag & UI_SELECT) but->iconadd = 1;
2602                                 else but->iconadd = 0;
2603                         }
2604                         break;
2605                         
2606                         /* quiet warnings for unhandled types */
2607                 default:
2608                         break;
2609         }
2610         
2611         
2612         /* safety is 4 to enable small number buttons (like 'users') */
2613         // okwidth = -4 + (BLI_rcti_size_x(&but->rect)); // UNUSED
2614         
2615         /* name: */
2616         switch (but->type) {
2617
2618                 case MENU:
2619                         if (BLI_rctf_size_x(&but->rect) > 24.0f) {
2620                                 /* only needed for menus in popup blocks that don't recreate buttons on redraw */
2621                                 if (but->block->flag & UI_BLOCK_LOOP) {
2622                                         if (but->rnaprop && (RNA_property_type(but->rnaprop) == PROP_ENUM)) {
2623                                                 int value = RNA_property_enum_get(&but->rnapoin, but->rnaprop);
2624                                                 const char *buf;
2625                                                 if (RNA_property_enum_name_gettexted(but->block->evil_C,
2626                                                                                      &but->rnapoin, but->rnaprop, value, &buf))
2627                                                 {
2628                                                         BLI_strncpy(but->str, buf, sizeof(but->strdata));
2629                                                 }
2630                                         }
2631                                 }
2632                                 BLI_strncpy(but->drawstr, but->str, sizeof(but->drawstr));
2633                         }
2634                         break;
2635
2636                 case NUM:
2637                 case NUMSLI:
2638
2639                         if (!but->editstr) {
2640                                 const char *drawstr_suffix = NULL;
2641                                 size_t slen;
2642
2643                                 UI_GET_BUT_VALUE_INIT(but, value);
2644
2645                                 slen = BLI_strncpy_rlen(but->drawstr, but->str, sizeof(but->drawstr));
2646
2647                                 if (ui_is_but_float(but)) {
2648                                         if (value == (double) FLT_MAX) {
2649                                                 slen += BLI_strncpy_rlen(but->drawstr + slen, "inf", sizeof(but->drawstr) - slen);
2650                                         }
2651                                         else if (value == (double) -FLT_MAX) {
2652                                                 slen += BLI_strncpy_rlen(but->drawstr + slen, "-inf", sizeof(but->drawstr) - slen);
2653                                         }
2654                                         /* support length type buttons */
2655                                         else if (ui_is_but_unit(but)) {
2656                                                 char new_str[sizeof(but->drawstr)];
2657                                                 ui_get_but_string_unit(but, new_str, sizeof(new_str), value, true, -1);
2658                                                 slen += BLI_strncpy_rlen(but->drawstr + slen, new_str, sizeof(but->drawstr) - slen);
2659                                         }
2660                                         else {
2661                                                 const int prec = ui_but_float_precision(but, value);
2662                                                 slen += BLI_snprintf(but->drawstr + slen, sizeof(but->drawstr) - slen, "%.*f", prec, value);
2663                                         }
2664                                 }
2665                                 else {
2666                                         slen += BLI_snprintf(but->drawstr + slen, sizeof(but->drawstr) - slen, "%d", (int)value);
2667                                 }
2668
2669                                 if (but->rnaprop) {
2670                                         PropertySubType pstype = RNA_property_subtype(but->rnaprop);
2671
2672                                         if (pstype == PROP_PERCENTAGE) {
2673                                                 drawstr_suffix = "%";
2674                                         }
2675                                         else if (pstype == PROP_PIXEL) {
2676                                                 drawstr_suffix = " px";
2677                                         }
2678                                 }
2679
2680                                 if (drawstr_suffix) {
2681                                         BLI_strncpy(but->drawstr + slen, drawstr_suffix, sizeof(but->drawstr) - slen);
2682                                 }
2683
2684                         }
2685                         break;
2686
2687                 case LABEL:
2688                         if (ui_is_but_float(but)) {
2689                                 int prec;
2690                                 UI_GET_BUT_VALUE_INIT(but, value);
2691                                 prec = ui_but_float_precision(but, value);
2692                                 BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s%.*f", but->str, prec, value);
2693                         }
2694                         else {
2695                                 BLI_strncpy(but->drawstr, but->str, UI_MAX_DRAW_STR);
2696                         }
2697                 
2698                         break;
2699
2700                 case TEX:
2701                 case SEARCH_MENU:
2702                 case SEARCH_MENU_UNLINK:
2703                         if (!but->editstr) {
2704                                 char str[UI_MAX_DRAW_STR];
2705
2706                                 ui_get_but_string(but, str, UI_MAX_DRAW_STR);
2707                                 BLI_snprintf(but->drawstr, sizeof(but->drawstr), "%s%s", but->str, str);
2708                         }
2709                         break;
2710         
2711                 case KEYEVT:
2712                 {
2713                         const char *str;
2714                         if (but->flag & UI_SELECT) {
2715                                 str = "Press a key";
2716                         }
2717                         else {
2718                                 UI_GET_BUT_VALUE_INIT(but, value);
2719                                 str = WM_key_event_string((short)value);
2720                         }
2721                         BLI_snprintf(but->drawstr, UI_MAX_DRAW_STR, "%s%s", but->str, str);
2722                         break;
2723                 }
2724                 case HOTKEYEVT:
2725                         if (but->flag & UI_SELECT) {
2726
2727                                 if (but->modifier_key) {
2728                                         char *str = but->drawstr;
2729                                         but->drawstr[0] = '\0';
2730
2731                                         if (but->modifier_key & KM_SHIFT)
2732                                                 str += BLI_strcpy_rlen(str, "Shift ");
2733                                         if (but->modifier_key & KM_CTRL)
2734                                                 str += BLI_strcpy_rlen(str, "Ctrl ");
2735                                         if (but->modifier_key & KM_ALT)
2736                                                 str += BLI_strcpy_rlen(str, "Alt ");
2737                                         if (but->modifier_key & KM_OSKEY)
2738                                                 str += BLI_strcpy_rlen(str, "Cmd ");
2739
2740                                         (void)str; /* UNUSED */
2741                                 }
2742                                 else {
2743                                         BLI_strncpy(but->drawstr, "Press a key", UI_MAX_DRAW_STR);
2744                                 }
2745                         }
2746                         else
2747                                 BLI_strncpy(but->drawstr, but->str, UI_MAX_DRAW_STR);
2748
2749                         break;
2750
2751                 case HSVCUBE:
2752                 case HSVCIRCLE:
2753                         break;
2754                 default:
2755                         BLI_strncpy(but->drawstr, but->str, UI_MAX_DRAW_STR);
2756                         break;
2757                 
2758         }
2759
2760         /* if we are doing text editing, this will override the drawstr */
2761         if (but->editstr)
2762                 but->drawstr[0] = '\0';
2763         
2764         /* text clipping moved to widget drawing code itself */
2765 }
2766
2767
2768 void uiBlockBeginAlign(uiBlock *block)
2769 {
2770         /* if other align was active, end it */
2771         if (block->flag & UI_BUT_ALIGN) uiBlockEndAlign(block);
2772
2773         block->flag |= UI_BUT_ALIGN_DOWN;
2774         block->alignnr++;
2775
2776         /* buttons declared after this call will get this align nr */ // XXX flag?
2777 }
2778
2779 static bool buts_are_horiz(uiBut *but1, uiBut *but2)
2780 {
2781         float dx, dy;
2782
2783         /* simple case which can fail if buttons shift apart
2784          * with proportional layouts, see: [#38602] */
2785         if ((but1->rect.ymin == but2->rect.ymin) &&
2786             (but1->rect.xmin != but2->rect.xmin))
2787         {
2788                 return true;
2789         }
2790
2791         dx = fabsf(but1->rect.xmax - but2->rect.xmin);
2792         dy = fabsf(but1->rect.ymin - but2->rect.ymax);
2793         
2794         return (dx <= dy);
2795 }
2796
2797 void uiBlockEndAlign(uiBlock *block)
2798 {
2799         block->flag &= ~UI_BUT_ALIGN;  /* all 4 flags */
2800 }
2801
2802 bool ui_but_can_align(uiBut *but)
2803 {
2804         return !ELEM(but->type, LABEL, OPTION, OPTIONN, SEPR, SEPRLINE);
2805 }
2806
2807 static void ui_block_do_align_but(uiBut *first, short nr)
2808 {
2809         uiBut *prev, *but = NULL, *next;
2810         int flag = 0, cols = 0, rows = 0;
2811         
2812         /* auto align */
2813
2814         for (but = first; but && but->alignnr == nr; but = but->next) {
2815                 if (but->next && but->next->alignnr == nr) {
2816                         if (buts_are_horiz(but, but->next)) cols++;
2817                         else rows++;
2818                 }
2819         }
2820
2821         /* rows == 0: 1 row, cols == 0: 1 column */
2822         
2823         /* note;  how it uses 'flag' in loop below (either set it, or OR it) is confusing */
2824         for (but = first, prev = NULL; but && but->alignnr == nr; prev = but, but = but->next) {
2825                 next = but->next;
2826                 if (next && next->alignnr != nr)
2827                         next = NULL;
2828
2829                 /* clear old flag */
2830                 but->drawflag &= ~UI_BUT_ALIGN;
2831                         
2832                 if (flag == 0) {  /* first case */
2833                         if (next) {
2834                                 if (buts_are_horiz(but, next)) {
2835                                         if (rows == 0)
2836                                                 flag = UI_BUT_ALIGN_RIGHT;
2837                                         else 
2838                                                 flag = UI_BUT_ALIGN_DOWN | UI_BUT_ALIGN_RIGHT;
2839                                 }
2840                                 else {
2841                                         flag = UI_BUT_ALIGN_DOWN;
2842                                 }
2843                         }
2844                 }
2845                 else if (next == NULL) {  /* last case */
2846                         if (prev) {
2847                                 if (buts_are_horiz(prev, but)) {
2848                                         if (rows == 0)
2849                                                 flag = UI_BUT_ALIGN_LEFT;
2850                                         else
2851                                                 flag = UI_BUT_ALIGN_TOP | UI_BUT_ALIGN_LEFT;
2852                                 }
2853                                 else {
2854                                         flag = UI_BUT_ALIGN_TOP;
2855                                 }
2856                         }
2857                 }
2858                 else if (buts_are_horiz(but, next)) {
2859                         /* check if this is already second row */
2860                         if (prev && buts_are_horiz(prev, but) == 0) {
2861                                 flag &= ~UI_BUT_ALIGN_LEFT;
2862                                 flag |= UI_BUT_ALIGN_TOP;
2863                                 /* exception case: bottom row */
2864                                 if (rows > 0) {
2865                                         uiBut *bt = but;
2866                                         while (bt && bt->alignnr == nr) {
2867                                                 if (bt->next && bt->next->alignnr == nr && buts_are_horiz(bt, bt->next) == 0) {
2868                                                         break;
2869                                                 }
2870                                                 bt = bt->next;
2871                                         }
2872                                         if (bt == NULL || bt->alignnr != nr) flag = UI_BUT_ALIGN_TOP | UI_BUT_ALIGN_RIGHT;
2873                                 }
2874                         }
2875                         else {
2876                                 flag |= UI_BUT_ALIGN_LEFT;
2877                         }
2878                 }
2879                 else {
2880                         if (cols == 0) {
2881                                 flag |= UI_BUT_ALIGN_TOP;
2882                         }
2883                         else {  /* next button switches to new row */
2884                                 
2885                                 if (prev && buts_are_horiz(prev, but))
2886                                         flag |= UI_BUT_ALIGN_LEFT;
2887                                 else {
2888                                         flag &= ~UI_BUT_ALIGN_LEFT;
2889                                         flag |= UI_BUT_ALIGN_TOP;
2890                                 }
2891                                 
2892                                 if ((flag & UI_BUT_ALIGN_TOP) == 0) {  /* stil top row */
2893                                         if (prev) {
2894                                                 if (next && buts_are_horiz(but, next))
2895                                                         flag = UI_BUT_ALIGN_DOWN | UI_BUT_ALIGN_LEFT | UI_BUT_ALIGN_RIGHT;
2896                                                 else {
2897                                                         /* last button in top row */
2898                                                         flag = UI_BUT_ALIGN_DOWN | UI_BUT_ALIGN_LEFT;
2899                                                 }
2900                                         }
2901                                         else 
2902                                                 flag |= UI_BUT_ALIGN_DOWN;
2903                                 }
2904                                 else 
2905                                         flag |= UI_BUT_ALIGN_TOP;
2906                         }
2907                 }
2908                 
2909                 but->drawflag |= flag;
2910                 
2911                 /* merge coordinates */
2912                 if (prev) {
2913                         /* simple cases */
2914                         if (rows == 0) {
2915                                 but->rect.xmin = (prev->rect.xmax + but->rect.xmin) / 2.0f;
2916                                 prev->rect.xmax = but->rect.xmin;
2917                         }
2918                         else if (cols == 0) {
2919                                 but->rect.ymax = (prev->rect.ymin + but->rect.ymax) / 2.0f;
2920                                 prev->rect.ymin = but->rect.ymax;
2921                         }
2922                         else {
2923                                 if (buts_are_horiz(prev, but)) {
2924                                         but->rect.xmin = (prev->rect.xmax + but->rect.xmin) / 2.0f;
2925                                         prev->rect.xmax = but->rect.xmin;
2926                                         /* copy height too */
2927                                         but->rect.ymax = prev->rect.ymax;
2928                                 }
2929                                 else if (prev->prev && buts_are_horiz(prev->prev, prev) == 0) {
2930                                         /* the previous button is a single one in its row */
2931                                         but->rect.ymax = (prev->rect.ymin + but->rect.ymax) / 2.0f;
2932                                         prev->rect.ymin = but->rect.ymax;
2933                                         
2934                                         but->rect.xmin = prev->rect.xmin;
2935                                         if (next && buts_are_horiz(but, next) == 0)
2936                                                 but->rect.xmax = prev->rect.xmax;
2937                                 }
2938                                 else {
2939                                         /* the previous button is not a single one in its row */
2940                                         but->rect.ymax = prev->rect.ymin;
2941                                 }
2942                         }
2943                 }
2944         }
2945 }
2946
2947 void ui_block_do_align(uiBlock *block)
2948 {
2949         uiBut *but;
2950         short nr;
2951
2952         /* align buttons with same align nr */
2953         for (but = block->buttons.first; but; ) {
2954                 if (but->alignnr) {
2955                         nr = but->alignnr;
2956                         ui_block_do_align_but(but, nr);
2957
2958                         /* skip with same number */
2959                         for (; but && but->alignnr == nr; but = but->next) {
2960                                 /* pass */
2961                         }
2962
2963                         if (!but) {
2964                                 break;
2965                         }
2966                 }
2967                 else {
2968                         but = but->next;
2969                 }
2970         }
2971 }
2972
2973 struct ColorManagedDisplay *ui_block_display_get(uiBlock *block)
2974 {
2975         return IMB_colormanagement_display_get_named(block->display_device);
2976 }
2977
2978 void ui_block_to_display_space_v3(uiBlock *block, float pixel[3])
2979 {
2980         struct ColorManagedDisplay *display = ui_block_display_get(block);
2981
2982         IMB_colormanagement_scene_linear_to_display_v3(pixel, display);
2983 }
2984
2985 void ui_block_to_scene_linear_v3(uiBlock *block, float pixel[3])
2986 {
2987         struct ColorManagedDisplay *display = ui_block_display_get(block);
2988
2989         IMB_colormanagement_display_to_scene_linear_v3(pixel, display);
2990 }
2991
2992 /**
2993  * \brief ui_def_but is the function that draws many button types
2994  *
2995  * \param x,y The lower left hand corner of the button (X axis)
2996  * \param width,height The size of the button.
2997  *
2998  * for float buttons:
2999  * - \a a1 Click Step (how much to change the value each click)
3000  * - \a a2 Number of decimal point values to display. 0 defaults to 3 (0.000)
3001  *      1,2,3, and a maximum of 4, all greater values will be clamped to 4.
3002  */
3003 static uiBut *ui_def_but(uiBlock *block, int type, int retval, const char *str,
3004                          int x, int y, short width, short height,
3005                          void *poin, float min, float max, float a1, float a2, const char *tip)
3006 {
3007         uiBut *but;
3008         int slen;