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