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