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