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