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