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