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