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