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