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